python中的字符串切割 maxsplit

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python中的字符串切割 maxsplit

LanLanDeMing   2022-12-20 我要评论

python 字符串切割 maxsplit

my_str.split(str1, maxsplit)

str1 可以不写,默认是空白字符(" " “\t” “\n”)

将my_str 这个字符串按照str1 进行切割, maxsplit 割几次

my_str = "hello world itcast and itcastcpp"
my_str1 = my_str.split(" ")
print(my_str1)

my_str2 = my_str.split(" ", 1)
print(my_str2)

my_str3 = my_str.split()  # 用的最多
print(my_str3)

my_str4 = my_str.split("itcast")
print(my_str4)


# 输出结果是
['hello', 'world', 'itcast', 'and', 'itcastcpp']
['hello', 'world itcast and itcastcpp']
['hello', 'world', 'itcast', 'and', 'itcastcpp']
['hello world ', ' and ', 'cpp']

python字符串切割split和rsplit函数

1. split(sep, maxsplit)

切分字符串,返回切分后的列表

sep,分隔符,默认空格

maxsplit,切分次数,默认最大次数,从起始位置开始计数

示例1:默认

s = 'a b c'
res = s.split()
res
['a', 'b', 'c']

示例2:指定参数

s = 'a b c'
res = s.split(sep=' ', maxsplit=1)
res
['a', 'b c']

示例3:位置参数

s = 'a.b.c'
res = s.split('.', 1)
res
['a', 'b.c']

2. rsplit(sep, maxsplit)

类似split,区别为从结尾位置开始计数

sep,分隔符,默认空格

maxsplit,切分次数,默认最大次数,从起始结尾开始计数

示例1:默认

s = 'a b c'
res = s.rsplit()
res
['a', 'b', 'c']

示例2:指定参数

s = 'a b c'
res = s.rsplit(sep=' ', maxsplit=1)
res
['a b', 'c']

示例3:位置参数

s = 'a.b.c'
res = s.rsplit('.', 1)
res
['a.b', 'c']

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们