
溫馨提示:手機(jī)觀看時,代碼塊可以左右滑動
字符串方法
- center 通過在兩邊添加填充字符(默認(rèn)為空格)讓字符串居中
b = "我想居中"
print(b.center(80))
print(b.center(80,"-"))
- find 在字符串中查找子串。如果找到,就返回子串的第一個字符的索引,否則返回-1
- index 在字符串中查找子串。如果找到,就返回子串的第一個字符的索引,否則引發(fā)ValueErorr異常
h = 'my name is Lexi'
print(h.find('m'))
print(h.index('n'))
#兩個函數(shù)都可限制搜索范圍
print(h.find('n',0,2)) #同時制定起點和終點
print(h.index('n',2)) #只制定了起點
- join 用于合并序列的元素
#合并一個字符串列表
sep = ["1","3","4","5"]
seq = '+'
seq.join(sep)
#用 join 地址拼接場景
dirs = '','usr','bin','env'
print('C:'+'\\'.join(dirs))
- lower 返回字符串的小寫版本
'Hello World'.lower()
'classical my girl'.title() #首詞大寫
#在string模塊中有個capwords可以實現(xiàn)首詞大寫
import string
string.capwords("that's your book")
- replace 將指定的子串都替換為另一個字符串,并返回替換后結(jié)果
'this is your book'.replace('is','eez')
- split 返回一個列表,按照分割符進(jìn)行劃分
'1+2+3+4+5'.split('+')
- strip 刪除指定字符
- rstrip 從右邊刪除指定字符
- lstrip 從左邊刪除指定字符
#去除輸入的空格
k = input("請輸入一個數(shù)字")
print(k.strip())
#去除指定的字符(只能去除開頭或者結(jié)尾的字符,中間的還是會被保留)
clear = '###$%%^^%$#^!#!$!'
print(clear.strip("#"))
上一篇:Python基礎(chǔ)筆記1-變量命名規(guī)則
下一篇:Python基礎(chǔ)筆記3-列表、元組、字典