将字符串拆分为多个字符(python)

2024-06-26 00:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,所以我知道每次出现字符/字符序列时,我都可以使用.split方法分割字符串-例如,在下面的代码中,当我使用.split方法时,每次出现:<string>都会被分割

<string>.split(":")

但是我不能给它多个参数,因此如果其中一个参数出现,字符串将被拆分

例如,给定此输入字符串:

input_string = """ \ hel\lo ="world"""

我想在每次出现\="<blank space>时分割input_string,以便获得以下输出:

['hel', 'lo', 'world']

我知道解决这个问题的办法是:

non_alfanumeric = """\\=" """
input_string = """ \ hel\lo ="world"""

for char in non_alfanumeric:
    input_string = input_string.replace(char, " ")

list = input_string.split(" ")
while "" in list:
    list.remove("")

但是如果输入字符串很长,那么计算速度会太慢,因为代码必须检查整个字符串4次:第一次检查\,第二次检查=,第三次检查",第四次检查<blank space>

其他解决方案是什么


Tags: 方法字符串代码loworldinput参数string
2条回答

你可能想看看正则表达式拆分,比如

import re

[x for x in re.split(r'[= \\"]+', """ \ hel\lo ="world""") if x]

看来re.split对你的案子有好处

相关问题 更多 >