用+
连接
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
word = 'love'
words = word*3
print(len(words))
# echo
12
字符串有点像一个元组,所以可以用string[index]
的方式进行索引
print(name[5:]) # 右侧不写,代表到最后
'me is Mike'
print(name[:5]) # 注意是左闭右开,所以第5个是取不到的
'My na'
从左到右,是和数组一样,从0开始的,而从右往左是从-1开始,具体索引方式如下
sub_num = '123'
phone_num = '138-1034-5123'
print(phone_num.find(sub_num))
# echo
10 # 返回第一次出现123这个字符串的位置,10是1的位置
phone_num = '138-1034-5123'
phone_num_new = phone_num.replace(phone_num[9:13],'*'*4)
print(phone_num_new)
# echo
138-1034-****
sub_num = '123'
phone_num = '138-1034-5123'
# 用type()函数确定变量类型
print(phone_num.find(sub_num),type(phone_num.find(sub_num)))
print(str(phone_num.find(sub_num)),type(str(phone_num.find(sub_num))))
# echo
10 <class 'int'> # find()返回的是int类型
10 <class 'str'> # str()强制转换成string字符串类型
a = 'I'
b = 'you'
print('{} love {} forever.'.format(a,b))
# echo
I love you forever.
lyric = 'The night begin to shine, the night begin to shine'
words = lyric.split()
print(words)
# echo
['The', 'night', 'begin', 'to', 'shine,', 'the', 'night', 'begin', 'to', 'shine'] # 注意:'shine,'后面跟了一个逗号!
默认split()
是根据空格划分的,可以使用split('\n')
根据换行来分割
fn.append(line.split('\n')[0]) # [0]表示分割后list的第一个元素
lyric = 'The night begin to shine, the night begin to shine'
words = lyric.split()
word = 'night'
print(words.count(word))
# echo
2 # 'night'出现了两次
string.punctuation
包含以下的特殊字符:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
使用strip(ch)
可以忽略ch
这些字符
string.lower()
可以将字符串全部转换成小写。
import string
lyric = 'The night begin to shine, the night begin to shine'
# 首先把字符串按照空格分开,切割成包含一个个string的list
# 接着使用列表解析式,对每个元素进行1)忽略特殊字符2)转换成小写单词
words = [word.strip(string.punctuation).lower() for word in lyric.split()]
print(words)
# echo
['the', 'night', 'begin', 'to', 'shine', 'the', 'night', 'begin', 'to', 'shine']