python中分割函数_Python-split()函数用法及简单实现

在Python中,split() 方法可以实现将一个字符串按照指定的分隔符切分成多个子串,这些子串会被保存到列表中(不包含分隔符),作为方法的返回值反馈回来。

split函数用法split(sep=None, maxsplit=-1)

参数

sep – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

maxsplit – 分割次数。默认为 -1, 即分隔所有。

实例:// 例子

String = 'Hello world! Nice to meet you'

String.split()

['Hello', 'world!', 'Nice', 'to', 'meet', 'you']

String.split(' ', 3)

['Hello', 'world!', 'Nice', 'to meet you']

String1, String2 = String.split(' ', 1)

// 也可以将字符串分割后返回给对应的n个目标,但是要注意字符串开头是否存在分隔符,若存在会分割出一个空字符串

String1 = 'Hello'

String2 = 'world! Nice to meet you'

String.split('!')

// 选择其他分隔符

['Hello world', ' Nice to meet you']

split函数实现def split(self, *args, **kwargs): # real signature unknown

"""

Return a list of the words in the string, using sep as the delimiter string.

sep

The delimiter according which to split the string.

None (the default value) means split according to any whitespace,

and discard empty strings from the result.

maxsplit

Maximum number of splits to do.

-1 (the default value) means no limit.

"""

pass

上图为Pycharm文档def my_split(string, sep, maxsplit):

ret = []

len_sep = len(sep)

if maxsplit == -1:

maxsplit = len(string) + 2

for _ in range(maxsplit):

index = string.find(sep)

if index == -1:

ret.append(string)

return ret

else:

ret.append(string[:index])

string = string[index + len_sep:]

ret.append(string)

return ret

if __name__ == "__main__":

print(my_split("abcded", "cd", -1))

print(my_split('Hello World! Nice to meet you', ' ', 3))

以上就是Python-split()函数用法及简单实现,希望能帮助到你哦~

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值