*可使字符串重复n次spa
1 print('hello world ' * 2) # hello world hello world
1 print('hello world'[2:]) # llo world
1 print('el' in 'hello') # True
1 name = 'Bob' 2 msg = 'my name is %s' % name 3 print(msg) # my name is Bob
采用+(建议尽可能不要采用此方法,效率低,时间复杂度为平方级)code
1 name = 'Bob' 2 age = '20' 3 msg = name + ' is ' + age + ' years old!' 4 print(msg) # Bob is 20 years old!
采用join方法blog
字符串是join前面的那一字符串为拼接间隔索引
1 name = 'Bob' 2 age = '20' 3 msg = name + ' is ' + age + ' years old!' 4 print(msg) # Bob is 20 years old! 5 msg_join = ' '.join([name, 'is', age, 'years old!']) 6 print(msg_join) # Bob is 20 years old!
6.1 count() 能够计算参数中的字符串在原字符串中出现的数量ip
1 string = 'hello kitty' 2 count = string.count('l') 3 print(count) # 2
6.2 center() 字符串
1 string = 'title' 2 msg = string.center(50, '-') 3 print(msg) # ----------------------title-----------------------
6.3 startswith()string
能够判断待处理的字符串是否是本身想要的字符串it
1 string = 'title' 2 print(string.startswith('t')) # True
6.4 find()class
查找参数中的字符串并返回索引,若找不到就返回-1效率
1 st = 'hello world' 2 index = st.find('w') 3 print(index) # 6 4 print(st.find('a')) # -1
6.5 index()
和find()差很少,只是在找不到的时候报错
1 st = 'hello world' 2 index = st.index('w') 3 print(index) # 6 4 print(st.index('a')) # ValueError: substring not found
6.6 lower()
将字符串中的大写字母变成小写字母
1 st = 'Hello World' 2 st_lower = st.lower() 3 print(st_lower) # hello world
6.7 upper()
将字符串中的小写字母变成大写字母
1 st = 'Hello World' 2 st_upper = st.upper() 3 print(st_upper) # HELLO WORLD
6.8 strip()
将待处理的字符串的空格,换行,制表符去掉
1 st = ' hello world\n' 2 st_strip = st.strip() 3 print(st_strip) # helloworld 4 print(len(st_strip)) # 11
6.9 replace()
1 st = 'hello world' 2 st_replace = st.replace('world', 'Bob') 3 print(st_replace) # hello Bob
6.10 split()
将字符串按照某字符进行分割,返回一个字符串元组
1 st = 'my old boy' 2 st_split = st.split(' ') 3 print(st_split) # ['my', 'old', 'boy']