【发布时间】:2020-04-21 14:07:29
【问题描述】:
我有一个字符串 -
"one:two:three:four:five:six:seven:eight".
现在我想用 ':' 分割这个字符串,但是直到前 3 次出现 ':'。
预期输出 -
['one','two','three','four:five:six:seven:eight'].
我该怎么做?
【问题讨论】:
标签: python python-3.x split
我有一个字符串 -
"one:two:three:four:five:six:seven:eight".
现在我想用 ':' 分割这个字符串,但是直到前 3 次出现 ':'。
预期输出 -
['one','two','three','four:five:six:seven:eight'].
我该怎么做?
【问题讨论】:
标签: python python-3.x split
split 采用除分隔符之外的 maxsplit 参数,这正是这样做的:
s.split(':',3)
# ['one', 'two', 'three', 'four:five:six:seven:eight']
【讨论】:
您可以使用 split for all 然后根据需要构建列表的形状。
str_list = "one:two:three:four:five:six:seven:eight"
my_list = str_list.split(":")
print([my_list[0], my_list[1], my_list[2], ":".join(my_list[3:])])
输出将是:
['one', 'two', 'three', 'four:five:six:seven:eight']
【讨论】:
或者如果你想使用正则表达式包:re
import re
re.split(':', "one:two:three:four:five:six:seven:eight", maxsplit=3)
# ['one', 'two', 'three', 'four:five:six:seven:eight']
如果你想编译正则表达式
import re
re_colon = re.compile(':')
re_colon("one:two:three:four:five:six:seven:eight", maxsplit=3)
# ['one', 'two', 'three', 'four:five:six:seven:eight']
【讨论】:
python 中的 split 函数可以接受 2 个参数,即 第一个参数是您必须用来拆分字符串的字符。 第二个参数是 max_split,一个整数,表示最大编号。分裂。
given_string = "one:two:three:four:five:six:seven:eight"
print(given_string.split(':',3))
【讨论】: