目录
字符串函数大合集
两端删除函数strip()
删除空白字符
删除两端指定字符
右端删除函数rstrip()
左端删除函数
字符串对齐
返回指定宽度字符串center()
原字符串居中对齐、左对齐、右对齐
字符串开始或结束符判定startswith()、endswith()
内置函数eval():尝试将任意字符串转化为表达式并求值。
字符串格式修饰
字符串元素判定
字符串处理的常用方法:字符串常量
字符串函数大合集
两端删除函数strip()
s.strip()
删除空白字符
s=" asd a "
print(s.strip())
删除两端指定字符
d='as dff gr esadwgr'
print(d.strip('a'))
右端删除函数rstrip()
s.rstrip()
左端删除函数
s.lstrip()
这三个函数的参数指定的字符串并不作为一个整体对待,而是在原字符串的两侧、右侧、左侧删除参数字符串中包含的所有字符,一层一层地从外往里扒。
print('aa12345678ffg'.strip('gaf'))
#'12345678'
print('aa12345678ffg'.strip('af'))
#'12345678ffg'
#字母f不在字符串两侧而不删除
print(str = “00000003210Runoob01230000000”__)
#3210Runoob0123
字符串对齐
返回指定宽度字符串center()
‘字符串内容’.center()
原字符串居中对齐、左对齐、右对齐
print('Hello world!'.center(20)) #居中对齐,以空格进行填充
#' Hello world! '
print('Hello world!'.center(20, '=')) #居中对齐,以字符=进行填充
#'====Hello world!===='
print('Hello world!'.ljust(20, '=')) #左对齐
#'Hello world!========'
print('Hello world!'.rjust(20, '=')) #右对齐
#'========Hello world!'
字符串开始或结束符判定startswith()、endswith()
s = 'Beautiful is better than ugly.'
print(s.startswith('Be')) #检测整个字符串
#True
print(s.startswith('Be', 5)) #指定检测范围起始位置
#False
print(s.startswith('Be', 0, 5)) #指定检测范围起始和结束位置
#True
内置函数eval():尝试将任意字符串转化为表达式并求值。
print(eval('3*6+5'))
简略计算,更好地将字符串便捷转换为表达式。
字符串格式修饰
zfill()返回指定宽度的字符串,在左侧以字符0进行填充。
>>> 'abc'.zfill(5) #在左侧填充数字字符0
#'00abc'
>>> 'abc'.zfill(2) #指定宽度小于字符串长度时,返回字符串本身
#'abc'
>>> 'uio'.zfill(20) #'00000000000000000uio
字符串元素判定
isalnum()、isalpha()、isdigit()、isdecimal()、isnumeric()、isspace()、 isupper()、 islower(),用来测试字符串是否为数字或字母、是否为字母、是 否为数字字符、是 否为空白字符、是否为大写字母以及是否为小写字母。
>>> '1234abcd'.isalnum() #全部为英文字母时返回True
#True
>>> '1234abcd'.isalpha()
#False
>>> '1234abcd'.isdigit()
#False
>>> 'abcd'.isalpha()
#True
>>> '1234.0'.isdigit()
#False
字符串处理的常用方法:字符串常量
Python标准库string中定义数字字符、标点符号、英文字母、大写字母、小写 字母等常量。
>>> import string
>>> string.digits
#'0123456789'
>>> string.punctuation
#'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.ascii_letters
#'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
#'abcdefghijklmnopqrstuvwxyz’
>>> string.ascii_uppercase
#'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#29