Python 字串的相關操作

2021-09-24 17:29:50 字數 2639 閱讀 2423

1.python中要求字串必須用引號括起來,單引號和雙引號的作用相同,只要配對即可。但在使用引號時需要留意一下幾種特殊情況

str1 = "i'm a coder"
str2 = '"spring is here, let us jam!", said woodchuck.'
str3 = '"we are scared, let\'s hide in the shade", says the bird'
2.拼接字串

s1 = "python "

s2 = "is funny"

s3 = s1 + s2

print(s3)#"python is funny"

s1 = "這本書的**是:"

p = 99.8

print(s1+str(p))

#使用str()將數值轉換成字串

print(s2+repr(p))

#使用repr()將數值轉換成字串

#repr()還有乙個功能,即以python表示式的形式來表示值

3.長字串

s = '''"let's go fishing",said mary.

"ok, let's go", said her brother.

they walked to a lake'''

print(s)

4.轉義字元

5.字串格式化

6.字串大小寫

a = "our domin is crazyit.org"

#每個單詞的首字母大寫

print(a.title())

#"our domin is crazyit.org"

#每個字母小寫

print(a.lower())

#"our domin is crazyit.org"

#每個字母大寫

print(a.upper())

#"our domin is crazyit.org"

7.刪除空白8.查詢、替換相關方法

s = "crazyit.org is a good site"

#判斷s是否以 crazit 開頭

print(s.startswith("crazyit"))

#判斷s是否以site結尾

print(s.endswith("site"))

#查詢s中"org"出現的位置

print(s.find("org"))

#查詢s中"org"出現的位置

print(s.index("org"))

#從索引2處開始查詢"org"出現的位置

print(s.find("org"),2)

#將字串中所有的it替換成***x

print(s.replace("it","***x"))

#將字串中的乙個it替換成***x

print(s.replace("it","***x",1))

#定義翻譯對映表:97->945,98->945,116->964

table =

print(s.translate(table))

9.分割、連線方法

s = "crazyit.org is a good site"

#使用空白對字串進行分割

print(s.plit())

#輸出['crazyit.org','is','a','good','site']

#使用空白對字串進行分割,最多隻分割前兩個單詞,後面作為整體

print(s.split(none,2))

#輸出['crazyit.org','is','a good site']

my_list = s.split()

#使用'/'作為分隔符,將my_list連線成字串

print('/'.join(my_list))

#輸出crazyit.org/is/a/good/site

#使用','作為分隔符,將my_list連線成字串

print(','.join(my_list))

Python字串的相關操作

判斷字串 s.isalnum 所有字元都是數字或者字母 s.isalpha 所有字元都是字母 s.isdigit 所有字元都是數字 s.islower 所有字元都是小寫 s.isupper 所有字元都是大寫 s.istitle 所有單詞都是首字母大寫,像標題 s.isspace 所有字元都是空白字元...

Python 字串相關操作函式

目錄 title upper lower rstrip replace split count 以首字母大寫的方式顯示每個單詞 name abc def print name.title 輸出結果 abc def 將字串改為全部大寫 name abc print name.upper 輸出結果 ab...

python基礎 字串的相關操作

1.統計字串長度 print len hello str 2.統計某乙個字串出現的次數 print hello str.count llo print hello str.count abc 3.某乙個字串出現的位置 print hello str.index llo 沒有會報錯 1.判斷空白字元 ...