Python分割字符串

Python分割字符串

hash070 312 2022-02-23

Python split()方法

在Python中,我们可以使用split()方法来处理字符串。

通过指定分隔符对字符串进行切片,如果参数num有指定值,则分割num+1个子字符串。

语法

str.split(str="", num=string.count(str)).

参数(Param)

  • str:分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)
  • num:分割次数,默认值为-1,即分割所有

返回(Return)

返回分割后的字符列表

实例(Example)

测试1

str = "helloworld,1,fe23"
print(str.split(','))

输出结果

['helloworld', '1', 'fe23']

测试2

str = "helloworld,1,fe23"
print(str.count(','))#一共有几个逗号
print(str.split(',',str.count(',')))

输出结果

2
['helloworld', '1', 'fe23']

可以看到,通过count方法,找到了2个逗号,然后split方法将返回3个字符串

关于python列表的文章:

https://hash070.top/python-list.html