python中的字符串切割 maxsplit

作者:LanLanDeMing 时间:2022-04-16 14:35:35 

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']

来源:https://blog.csdn.net/LanlanDeming/article/details/103318399

标签:python,字符串,切割,maxsplit
0
投稿

猜你喜欢

  • Python基于辗转相除法求解最大公约数的方法示例

    2023-08-24 19:47:35
  • 使用php将某个目录下面的所有文件罗列出来的方法详解

    2023-09-29 10:47:05
  • 详谈python3中用for循环删除列表中元素的坑

    2023-08-01 06:04:31
  • Python深度优先算法生成迷宫

    2023-05-13 08:38:09
  • php使用pack处理二进制文件的方法

    2023-11-21 04:26:11
  • django写单元测试的方法

    2021-02-04 19:17:28
  • Django 用户登陆访问限制实例 @login_required

    2021-05-26 07:31:22
  • 解决pycharm中导入自己写的.py函数出错问题

    2023-07-09 12:12:05
  • 异步加载Google Adsense 更新到Wordpress 2.62

    2008-09-11 13:09:00
  • Mysql触发器处理本表数据

    2010-10-25 19:56:00
  • Python还能这么玩之用Python修改了班花的开机密码

    2023-11-23 17:38:40
  • Python3开发环境搭建详细教程

    2023-11-12 10:46:28
  • Python如何生成随机高斯模糊图片详解

    2021-08-25 13:07:18
  • 用Python实现web端用户登录和注册功能的教程

    2021-03-03 07:49:09
  • 使用pytorch进行张量计算、自动求导和神经网络构建功能

    2022-08-18 11:50:48
  • GC与JS内存泄露

    2010-09-25 19:01:00
  • Python+selenium破解拼图验证码的脚本

    2023-11-22 05:24:05
  • 使用pytorch搭建AlexNet操作(微调预训练模型及手动搭建)

    2023-05-04 05:09:51
  • Django模板标签{% for %}循环,获取制定条数据实例

    2023-02-25 02:27:59
  • Python OpenCV实现图形检测示例详解

    2023-05-23 15:36:39
  • asp之家 网络编程 m.aspxhome.com