python拆分字符串(.split),以及连接字符串(.join)。

本文介绍了Python中字符串处理的基础方法,包括str.split和.join函数的使用。通过实例演示如何使用这些函数来分割和组合字符串,适用于初学者及需要复习基础知识的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1,str.split官方文档如下:

str.split(sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string. 
If maxsplit is given, at most maxsplit splits are done (thus, 
the list will have at most maxsplit+1 elements). 

If maxsplit is not specified or -1, 
then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are 
deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). 

The sep argument may consist of multiple characters (for example, 
'1<>2<>3'.split('<>') returns ['1', '2', '3']). 

Splitting an empty string with a specified separator returns ['']

  seq是分隔符,如'_','.'等。maxsplit是分隔次数,如为1,就从第一个出现分隔符的地方分隔一次,则字符串就变成两串了。
  例子如下:

>>> a = 'x_y_z_a_b_c'
>>> a.split(sep='_', maxsplit=1)     # 拆一次,分隔符为_
['x', 'y_z_a_b_c']

>>> a.split(sep='_', maxsplit=2)     # 拆两次
['x', 'y', 'z_a_b_c']

>>> a.split(sep='_', maxsplit=-1)    # 全拆
['x', 'y', 'z', 'a', 'b', 'c']

  2,.join。把字符串用设定的连接符连接起来。例子如下:

>>> a = 'x_y_z_a_b_c'
>>> b = a.split(sep='_', maxsplit=-1)[0:-1]    # 全拆之后,取第一至倒数第二的str
['x', 'y', 'z', 'a', 'b']

>>> '_'.join(b)    # 用_把str连接起来。
'x.y.z.a.b'

>>> ''.join(b)     # 用空白连接起来
'xyzab'


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值