# 示例代码:split在Python中的用法
# split() 方法通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串
# 参数:
# - sep: 分隔符。默认为空格或换行符等空白字符。可以指定分隔符,如逗号、分号等。
# - maxsplit: 分割次数。默认为 -1, 即不分割次数。
text = "hello, world! welcome to python"
# 使用空格作为分隔符,默认分割所有
result1 = text.split()
print(result1) # 输出: ['hello,', 'world!', 'welcome', 'to', 'python']
# 使用逗号作为分隔符
result2 = text.split(',')
print(result2) # 输出: ['hello', ' world! welcome to python']
# 使用空格作为分隔符,并指定最大分割次数为1
result3 = text.split(' ', 1)
print(result3) # 输出: ['hello,', 'world! welcome to python']
# 使用多个字符作为分隔符
import re
text_with_multiple_separators = "hello, world! welcome;to:python"
result4 = re.split(r'[,\s;:]+', text_with_multiple_separators)
print(result4) # 输出: ['hello', 'world!', 'welcome', 'to', 'python']
上一篇:python sleep
下一篇:python map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站