Python 字符串内置函数(五)

# 5.字符串分隔
# strip()函数用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
str = "00000003210Runoob01230000000";
print(str.strip('0')) # 去除首尾字符 0

str2 = " Runoob "; # 去除首尾空格
print(str2.strip())
'''
运行结果:
3210Runoob0123
Runoob
'''

# lstrip()函数用于截掉字符串左边的空格或指定字符。
str = " this is string example....wow!!! ";
print(str.lstrip())
str = "88888888this is string example....wow!!!8888888";
print(str.lstrip('8'))
'''
运行结果:
this is string example....wow!!!
this is string example....wow!!!8888888
'''

# rstrip()函数删除字符串末尾的指定字符(默认为空格).
str = " this is string example....wow!!! ";
print(str.rstrip())
str = "88888888this is string example....wow!!!8888888";
print(str.rstrip('8'))
'''
运行结果:
this is string example....wow!!!
88888888this is string example....wow!!!
'''

# split()函数通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
'''
str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num -- 分割次数。默认为 -1, 即分隔所有。
'''
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print(str.split( )) # 以空格为分隔符,包含 \n
print(str.split(' ', 1 )) # 以空格为分隔符,分隔成两个
'''
运行结果:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
'''
# rsplit()函数从右侧开始将字符串拆分为列表。

# splitlines()函数按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
'''
在输出结果里是否保留换行符('\r', '\r\n', \n'),默认为 False,不包含换行符,如果为 True,则保留换行符
'''
str1 = 'ab c\n\nde fg\rkl\r\n'
print(str1.splitlines())

str2 = 'ab c\n\nde fg\rkl\r\n'
print(str2.splitlines(True))
'''
运行结果:
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
'''

猜你喜欢

转载自www.cnblogs.com/shnuxiaoan/p/12934608.html
今日推荐