python常用字符串方法调用语法_Python3常用的字符串方法
判斷是否全是字母
"python".isalpha() # 返回True
"2python".isalpha() # 返回False
根據分隔符分割字符串
a = "I,LOVE,PYTHON"
a.split(",")
# 結果:['I','LOVE','PYTHON']
去掉字符串兩頭的空格及回車符
str.strip() # 去掉字符串兩邊的空格及回車符
str.lstrip() # 去掉字符串左邊的空格及回車符
str.rstrip() # 去掉字符串右邊的空格及回車符
字符大小寫的轉換
str.upper() # 字母轉化為大寫
str.lower() # 字母轉化為小寫
str.capitalize() # 將首字母轉化為大寫
str.isupper() # 判斷字母是否全是大寫
str.islower() # 判斷字母是否全是小寫
str.istitle() # 判斷字符串中是否所有單詞的首字母為大寫,且其他字母為小寫
用join()拼接字符串
s_list = ['www','baidu','com']
"*".join(s_list)
# 返回結果:'www*baidu*com'
用center()方法填充字符串
str = 'runoob'
str.center(20, '*') # str.center(width[, fillchar])
# 返回結果:'*******runoob*******'
統計字符串里某個字符出現的次數
# 語法:str.count(sub, start= 0,end=len(string))
str = "this is string example....wow!!!";
sub = "wow";
print str.count(sub)
# 返回結果:1
用于判斷字符串是否以指定后綴結尾
"""
語法:str.endswith(suffix[, start[, end]])
參數
suffix -- 該參數可以是一個字符串或者是一個元素。
start -- 字符串中的開始位置。
end -- 字符中結束位置。
"""
str = "this is string example....wow!!!";
suffix = "wow!!!";
print str.endswith(suffix);
# 返回結果:True
find()方法檢測字符串中是否包含子字符串
如果包含子字符串返回開始的索引值,否則返回-1
"""
語法:
str.find(str, beg=0, end=len(string))
參數
str -- 指定檢索的字符串
beg -- 開始索引,默認為0。
end -- 結束索引,默認為字符串的長度。
"""
str1 = "this is string example....wow!!!";
str2 = "exam";
print str1.find(str2);
# 結果:15,查不到返回-1
index()方法方法檢測字符串中是否包含子字符串
用法與 find() 方法一樣,如果包含子字符串返回開始的索引值,不同的是找不到子字符串會拋出異常。
把字符串中的 old(舊字符串) 替換成 new(新字符串)
"""
語法:
str.replace(old, new[, max])
參數
old -- 將被替換的子字符串。
new -- 新字符串,用于替換old子字符串。
max -- 可選字符串, 替換不超過 max 次
"""
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was"); # 結果:thwas was string example....wow!!! thwas was really string
print str.replace("is", "was", 3); # 結果:thwas was string example....wow!!! thwas is really string
總結
以上是生活随笔為你收集整理的python常用字符串方法调用语法_Python3常用的字符串方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python docx runs_别再问
- 下一篇: python怎么爬虎牙_使用python