
字符串操作
string典型的内置方法:
- count()
- center()
- startswith()
- find()
- format()
- lower()
- upper()
- strip()
- replace()
- split()
- join()
count()
计数,查询字符串中出现指定字符的次数。
st='hello kitty' print(st.count('l'))
输出:2
center()
字符串居中。其中,50表示新字符串长度,'#'表示填充字符。
st='hello kitty'
print(st.center(50,'#'))
输出:
###################hello kitty####################
startswith()
判断是否以某个内容开头。
st='hello kitty'
print(st.startswith('he'))
输出:True
find()
查找到第一个元素,并将索引值返回。
st='hello kitty'
print(st.find('t'))
输出:8
format()
格式化输出的一种方式。(另一种方式在字符串中加%d、%s、%f,字符串外加%变量名)
st='hello kitty {name} is {age}'
print(st.format(name='alex',age=37))
输出:
hello kitty alex is 37
lower()
将字符串中的大写全部变成小写。
print('My tLtle'.lower())
输出:
my tltle
upper()
将字符串中的小写全部变成大写。
print('My tLtle'.upper())
输出:
MY TLTLE
strip()
将字符串中的制表符、换行符等不可见字符去掉。
print('\tMy tLtle\n'.strip())
输出:
My tLtle
replace()
将字符串中第1个'itle'替换为'lesson'。
print('My title title'.replace('itle','lesson',1))
输出:
My tlesson title
split()
以字符串中的第1个i为分隔符,将字符串分割为两部分,并放入列表中。
print('My title title'.split('i',1))
输出:
['My t', 'tle title']
详细解释:
join()
字符串拼接最好的方法。需要注意的是,join()中必须是一个列表。
str1 = 'Alex'
str2 = 'Oliver'
a = ''.join([str1,' and ',str2])
print(a)
输出:
Alex and Oliver
Python查看帮助的方法
>>> help(str)
>>> help(str.split)
>>> help(int)
小练习
统计str字符串中每个字符的个数并打印。
str = 'U2FsdGVkX1+xaZLZ3hGZbZf40vPRhk+j+FHIHiopidA8GG6aolpjAU7kVHuLMYcJ'
# 方法1:
b = {}
for i in str:
if i in b:
b[i] += 1
else:
b.setdefault('%s'%i,1)
for i,v in b.items():
print("字符串:%s,个数:%d"%(i,v))
#方法2
dic = {}
for i in str:
if i in dic:continue
else:
dic.setdefault(i,str.count(i))
print(i,str.count(i))