Python 小白入門字串

2021-10-11 09:08:57 字數 3411 閱讀 7968

字元拼接

長度計算

字元擷取

字元分割

字元鄰接

字元匹配

字元轉換

字元格式化

字元編碼

正規表示式入門

#字元拼接

a="hello"

b="world"

print

(a+"-"

+b)#不同型別的可以先轉換再做運算

print

(a+str

(123

))

#長度的計算:

print

(len

(a))

print

(len

(b))

c="猜一下,字元多長"

print

(len

(c))

#計算字元長度

#擷取:和序列的索引操作類似

print

(b[1:3

])

#分割:字串物件.split(分割符號)

d="1 2 3 4 5"

.split(

)print

(d)e=

"3,5,8,9,8"

print

(e.split(

",")

)

#鄰接:連線符號.join(字串列表)

f="&"

.join(

["9"

,"8"

,"7"

,"6"])

print

(f)#綜合

g=f.split(

"&")

h="#"

.join(g)

print

(h)

檢索:count->字元個數

find->字元第一次出現的位置,查詢不到會返回-1

index->字元第一次出現位置的索引,找不到會報錯

rindex->從右往左找

startswitch()->以「 」開頭,返回bool型別

endswitch()->以「 」結尾,返回bool型別

print

(a.count(

"l")

)print

(a.find(

"l")

)print

(a.index(

"ll"))

print

(a.index(

"o")

)print

(a.rindex(

"l")

)print

(b.startswith(

"wor"

))

#字元大小寫的轉換:upper()、lower()

print

(a.upper())

i=a.upper(

)print

(i.lower())

#去除空白符:strip()、lstrip()、rstrip()

a1=" hello "

print

(a1.strip())

a2="###hello###"

print

(a2.lstrip(

"#")

)print

(a2.rstrip(

"#")

)

#格式化%format

print

("我叫%s,我今年%d歲了,身高%f公尺,我來自%s"%(

"小明",9

,1.46

,"廈門"))

print

("這兒有乙個%d"%11

)print

("這兒有乙個%08d"%11

)print

("這兒有乙個%.2f"

%11.46

)print

("我叫{},我今年{}歲了,身高{}公尺,我來自{}"

.format

("小明",9

,1.46

,"廈門"))

輸出類似銀行的金額:

print

("今日存入金額¥元"

.format

(1000012345.89123

))

輸出結果:

今日存入金額¥1

,000

,012

,345.89元

兩個佔位符共用乙個引數:

print

("的十六進製制"

.format

(100

))

三個編碼、兩個方法:

編碼:utf-8、gbk、gb2312

encode方法:字串str->位元組流bytes

decode方法:位元組流bytes->字元流str

a3=

"人生苦短,我用python"

print

(len

(a3)

)print

(len

(a3.encode(

"utf-8"))

)print

(len

(a3.encode(

"gbk"))

)a4=a3.encode(

"utf-8"

)a5=a3.encode(

"gbk"

)print

(a4.decode())

print

(a5.decode(

"gbk"

))

正規表示式初入門:

importmodule

import re

a6="123456"

a7="789654"

a8="1234567"

print

(re.match(r"\d"

,a6)

)print

(re.match(r"\d"

,a7)

)# 從頭到尾匹配成功輸出$

print

(re.match(r"\d$"

,a8)

)a9=

"800555"

print

(re.match(r"8\d$"

,a9)

)a10=

"13700000000"

print

(re.match(r"1[^012]\d$"

,a10)

)

python入門 字串

x i.upper if i.islower else i.lower for i in s print join x 或者是 s.swapcase sample input this is a string sample output this is a string def split and ...

小白入門筆記 C 字串填充

使用下列 string 方法之一建立新的字串,其中包含原始字串以及用於填充原始字串使其達到指定總長度的前導或尾隨字元。填充字元可以是空格或指定字元,因此可顯示為右對齊或左對齊。方法名使用string.padleft 用前導字元填充字串使其達到指定的總長度。string.padright 用尾隨字元填...

Python快速入門 字串

1 字串的三種方式 單引號str value 三木成森 雙引號str value 三木成森 三引號str value 三木成森 str value 三木成森 這種一般用來注釋 python字串不允許更改,向乙個索引賦值會發生錯誤 2 轉義字元 轉義字元 轉義字元 代表含義 在行尾時 反斜槓符號 反斜...