python基础语法之字符串
1 字符串中*的使用
*可以使字符串重复n次
1 print('hello world ' * 2) # hello world hello world
2 索引获取字符串的字符元素
1 print('hello world'[2:]) # llo world
3 in成员符
1 print('el' in 'hello') # True
4 字符串格式化
1 name = 'Bob' 2 msg = 'my name is %s' % name 3 print(msg) # my name is Bob
5 字符串拼接
采用+(建议尽量不要采用此方法,效率低,时间复杂度为平方级)
1 name = 'Bob' 2 age = '20' 3 msg = name + ' is ' + age + ' years old!' 4 print(msg) # Bob is 20 years old!
采用join方法
字符串是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 字符串常用的内置方法
6.1 count() 可以计算参数中的字符串在原字符串中出现的数量
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()
可以判断待处理的字符串是不是自己想要的字符串
1 string = 'title' 2 print(string.startswith('t')) # True
6.4 find()
查找参数中的字符串并返回索引,若找不到就返回-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']