gpt4 book ai didi

python - split() Python 中的多个指定分隔符

转载 作者:行者123 更新时间:2023-12-03 21:58:35 24 4
gpt4 key购买 nike

如何在python中的split()中指定多个分隔符?

input = "print{hello world};x = 2 + 3;"
x = input.split('{') #this works but not the desired OP
x = input.split('{','}') #error
x = input.split('{}') #this works but not the desired OP

所需的操作:
['print', 'hello world', ';x = 2 + 3;']

最佳答案

你可以使用 re.split通过这种方式:

import re

my_input = "print{hello world};x = 2 + 3;"
re.split('{|}', my_input)

输出:
['print', 'hello world', ';x = 2 + 3;']

关于python - split() Python 中的多个指定分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60800025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com