Python Basic -rsplit( )、split( )、splitlines()

文章目录

  • 先定义几个字符串变量
    • rsplit( )--以指定字符将字符串分割成多段,默认情况下,只要是匹配到的字符就分,从右往左找,分割符被逗号取代,返回值为列表
    • split( )--比较上一个就是从左开始查找关键字,并以关键字进行拆分,从左往右查找
    • splitlines()-将一行字符串分割成多行,并且返回到一个列表中,分割符为\r,\n 可以选择是否保留分割符
      • 查看全部内置字符串处理方法,请点击

先定义几个字符串变量

string1 = "Hello,World."
string2 = "Python is the best computer language"
string3 = "Python is the language that the most easy of the\tworld."
string4 = "3 is bigger than 1"
string5 = "Python is the {what} that the most {how} of the world."

rsplit( )–以指定字符将字符串分割成多段,默认情况下,只要是匹配到的字符就分,从右往左找,分割符被逗号取代,返回值为列表

print(string3.rsplit("the"))            # 以指定字符将字符串分割成多段,默认情况下,只要是匹配到的字符就分,从右往左找,分割符被逗号取代,返回值为列表
print(string3.rsplit("the",2))            # 以指定字符将字符串分割成多段,默认情况下,只要是匹配到的字符就分,分割符被逗号取代,返回值为列表,默认值为-1,表示不限制,2表示找两个分割符
print(string3.rsplit("the",1))            #

"""
['Python is ', ' language that ', ' most easy of ', '\tworld.']
['Python is the language that ', ' most easy of ', '\tworld.']
['Python is the language that the most easy of ', '\tworld.']
"""

split( )–比较上一个就是从左开始查找关键字,并以关键字进行拆分,从左往右查找

print("*".center(100,"*"))
print(string3.split("the"))             # 比较上一个就是从左开始查找关键字,并以关键字进行拆分,从左往右查找
print(string3.split("the",2))           # 2为maxsplit,最多找2个分割符,从左往右查找
print(string3.split("the",-1))          # -1 为默认值,不高上限
print(string3.split("the",1))           # 最多查找1个关键字
"""
['Python is ', ' language that ', ' most easy of ', '\tworld.']
['Python is ', ' language that ', ' most easy of the\tworld.']
['Python is ', ' language that ', ' most easy of ', '\tworld.']
['Python is ', ' language that the most easy of the\tworld.']

"""

splitlines()-将一行字符串分割成多行,并且返回到一个列表中,分割符为\r,\n 可以选择是否保留分割符

# 将一行字符串分割成多行,并且返回到一个列表中,分割符为\r,\n 可以选择是否保留分割符
string30 = "Python is the\n language\r.that the\r most easy\n of the world."
print("*".center(100,"*"))
print(string30.splitlines())
print(string30.splitlines(keepends=True))
"""
****************************************************************************************************
['Python is the', ' language', '.that the', ' most easy', ' of the world.']
['Python is the\n', ' language\r', '.that the\r', ' most easy\n', ' of the world.']

"""

查看全部内置字符串处理方法,请点击

你可能感兴趣的:(Python,python,字符串)