文章目录
- 1 字符串用 + 和 * 连接
- 2 len(string)——计算字符串的长度
- 3 string[left,right]——字符串的分片与索引
- 4 string.find(sub_string)——查找子字符串出现的位置
- 5 string.replace(string_a,string_b)——替换部分字符串
- 6 str(int_a)——强制类型转换
- 7 '{} and {}'.format(string_a,string_b)——字符串格式化符
- 8 strings.split()——分割字符串中的单词
- 9 strings.count(string)——统计字符string出现的次数
- 10 strings.strip(string.punctuation).lower()——忽略字符,转换小写
1 字符串用 + 和 * 连接
用+
连接
what_he_does = ' plays '
his_instrument = 'guitar'
his_name = 'Robert Johnson'
artist_intro = his_name + what_he_does + his_instrument
print(artist_intro)
# echo
Robert Johnson plays guitar
用*
连接
word = 'love'
words = word*3
print(words)
# echo
lovelovelove
2 len(string)——计算字符串的长度
word = 'love'
words = word*3
print(len(words))
# echo
12
3 string[left,right]——字符串的分片与索引
字符串有点像一个元组,所以可以用string[index]
的方式进行索引
print(name[5:]) # 右侧不写,代表到最后
'me is Mike'
print(name[:5]) # 注意是左闭右开,所以第5个是取不到的
'My na'
从左到右,是和数组一样,从0开始的,而从右