在Python中,字符串是最常用的基本数据类型,我们可以使用引号来创建字符串。而且创建字符串很简单,只要为变量分配一个值即可,几乎在每个Python程序中都会使用到它。本文为大家总结一下“Python必备的字符串方法”,一起来看看吧。 1、Slicing Slicing切片,按照一定条件从列表或者元组中取出部分元素。 s = ' hello ' s = s[:] print(s) # hello s = ' hello ' s = s[3:8] print(s) # hello 2、strip() strip()方法用于移除字符串头尾指定的字符或字符序列。 s = ' hello '.strip() print(s) # hello s = '###hello###'.strip() print(s) # ###hello### 3、lstrip() 移除字符串左侧指定的字符或字符序列。 s = ' hello '.lstrip() print(s) # hello 同样的,可以移除左侧所有包含在字符集中的字符串。 s = 'Arthur: three!'.lstrip('Arthur: ') print(s) # ee! 4、rstrip() 移除字符串右侧指定的字符或字符序列。 s = ' hello '.rstrip() print(s) # hello 5、removeprefix() python3.9中移除前缀的函数。 # python 3.9 s = 'Arthur: three!'.removeprefix('Arthur: ') print(s) # three! 6、removesuffix() Python3.9中移除后缀的函数。 s = 'HelloPython'.removesuffix('Python') print(s) # Hello 7、replace() 把字符串中的内容替换成指定的内容。 s = 'string methods in python'.replace(' ', '-') print(s) # string-methods-in-python s = 'string methods in python'.replace(' ', '') print(s) # stringmethodsinpython 8、re.sub() re是正则的表达式,sub是substitute表示替换。 re.sub则是相对复杂点的替换。 import re s = "string methods in python" s2 = s.replace(' ', '-') print(s2) # string----methods-in-python s = "string methods in python" s2 = re.sub("\s+", "-", s) print(s2) # string-methods-in-python 9、split() 对字符串做分隔处理,最终的结果是一个列表。 s = 'string methods in python'.split() print(s) # ['string', 'methods', 'in', 'python'] 10、rsplit() 从右侧开始对字符串进行分隔。 s = 'string methods in python'.rsplit(' ', maxsplit=1) print(s) # ['string methods in', 'python'] 11、join() string.join(seq)。以string作为分隔符,将seq中所有的元素合并为一个新的字符串。 list_of_strings = ['string', 'methods', 'in', 'python'] s = '-'.join(list_of_strings) print(s) # string-methods-in-python list_of_strings = ['string', 'methods', 'in', 'python'] s = ' '.join(list_of_strings) print(s) # string methods in python 12、upper() 将字符串中的字母,全部转换为大写。 s = 'simple is better than complex'.upper() print(s) # SIMPLE IS BETTER THAN COMPLEX 13、lower() 将字符串中的字母,全部转换为小写。 s = 'SIMPLE IS BETTER THAN COMPLEX'.lower() print(s) # simple is better than complex 14、capitalize() 将字符串中的首个字母转换为大写。 s = 'simple is better than complex'.capitalize() print(s) # Simple is better than complex 15、islower() 判断字符串中的所有字母是否都为小写,是则返回True,否则返回False。 print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False print('simple is better than complex'.islower()) # True 16、isupper() 判断字符串中的所有字母是否都为大写,是则返回True,否则返回False。 print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True print('SIMPLE IS BETTER THAN complex'.isupper()) # False |
|
来自: 老男孩IT教育 > 《Python培训》