str常用命令:字元操作:.capitalize() .upper() .lower() .title() .swapcase()
判斷:.startwith() .endwith() .isalnum() .isalpha() .isdigit()
統計:.count() len()
索引:.find() .index()
結構:.format() .strip() .lstrip() .rstrip() .split() .replace .center() .expandtabs()
迴圈:for
1,首字母大寫:
s.capitalize()
s1 = 'python is good
's2 =s1.capitalize()
print(s2)
2,全部大寫:s.upper()
s1 = 'python is good
's2 =s1.upper()
print(s2)
3,全部小寫s.lower()
s1 = 'python is good
's2 =s1.lower()
print(s2)
result:python is good4,大小寫翻**
s.swapcase()
s1 = 'python is good
's2 =s1.swapcase()
print(s2)
result:python is good5,每個分隔的單詞首字母大寫:
s.title()
s1 = 'python is good
's2 =s1.title()
print(s2)
result:python is good6,字串居中:
s.center(20)--20代表輸出寬度
s1 = 'python is good
's2 = s1.center(20)
print(s2)
s.center(20,'-')--符號代表填充內容
s1 = 'python is good
's2 = s1.center(20,'-'
)print(s2)
7,自動填充,當字串中有\t(tab鍵),前面不足8位的補充到8位,不足16未補充到16位:s.expandtabs()
8,字串長度:
len(s)--長度
s1 = 'python is good
's2 =len(s1)
print(s2)
result:149,判斷字串以什麼開頭/結尾:
s.startwith('e',start='',end='')--e表示查詢物件,start/end切片定位,返回true/faulse
s1 = 'python is good
's2 = s1.startswith('o'
)print(s2)
result:false
s1 = 'python is good
's2 = s1.startswith('p'
)print(s2)
result:true
s1 = 'python is good
's2 = s1.startswith('
p',2,5)
print(s2)
result:falses.endwith('')--同理
10.根據元素找索引:
s.find('')--返回元素位置索引,未找到返回-1.
s1 = 'python is good
's2 = s1.find('s'
)print(s2)
result:8
s1 = 'python is good
's2 = s1.find('w'
)print(s2)
result:-1s.index('')--同理,未找到報錯
s1 = 'python is good
's2 = s1.index('w'
)print(s2)
result:valueerror: substring not found
s1 = 'python is good
's2 = s1.index('s'
)print(s2)
result:811,去掉空格:常用於有使用者輸入的地方
s.strip()--去掉前後空格
s1 = 'python is good
's2 =s1.strip()
print(s2)
result:python is goods.strip('%')--%表示要去掉的所有元素,可多個元素-%q,也可有空格- %q
s.lstrip()--去掉前端空格
s1 = 'python is good
's2 =s1.lstrip()
print(s2)
result:python is goods.rstrip()--去掉尾部空格
s1 = 'python is good
's2 =s1.rstrip()
print(s2)
result: python is good*strip的坑:
python基礎之字串
1.單引號字串和轉義引號 在python中,字串是用單引號或者雙引號括起來,在表示字串的時候,單引號和雙引號有什麼區別嗎?事實上並沒有。在某些特殊情況時候,單引號和雙引號是不能換線交換的,比如在乙個字串中包含了雙引號,那麼這個字串就必須用單引號括起來,反之,乙個字串中包含了單引號,那麼這個字串就必須...
python基礎之字串
1.基本字串的操作 所有標準序列的操作 索引,分片,乘法,成員資格判斷,求長度,取最小和最大值 同樣適用,但是記住 字串都是不可變的。2.字串格式化 精簡版 字串的格式化可以使用字串格式化操作符 百分號 來實現。在 的左側放置乙個字串 格式化字串 而右側放置希望被格式化的值。可以使用乙個值,如乙個字...
python基礎之字串
字串的鏈結操作 用 字串的複製操作 用 字串的索引操作 通過索引可以訪問制定的位置的字元,索引從0開始 索引 列如 a hello world print a 0 輸出的結果 是 h 字串的擷取操作 完整格式 開始索引 結束索引 間隔值 從開始擷取到索引結束之前 結束索引之前 從開始索引擷取到字串最...