将字符串加引号括起来

问题描述 投票:0回答:1

我有以下字符串:

"'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"

我正在使用shlex.split如下标记字符串:

for element in shlex.split("'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"):
    print(element)

这是输出:

string
4
[RP0, LC0]
[3, 4]
[3, 4]

但是我正在寻找以下输出:

string
4
['RP0', 'LC0']
[3, 4]
[3, '4']

这可行吗?

python python-3.x tokenize
1个回答
0
投票

我不知道像shlex这样的库会如此灵活,而我认为正则表达式并不简单,我宁愿避免嵌套嵌套的正则表达式。

所以我们可以在纯python中以相对简单的方式尝试它,但是它离pythonic答案还很远:

myInput = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myInput.__iter__()
for idx, char in enumerate(word_iterator):
    if char == "'":
        continue

    processedInput+=char

    if char == '[':
        next_char=word_iterator.__next__()
        while(next_char != "]"):
          processedInput+=next_char
          next_char=word_iterator.__next__()
        else:
          processedInput+=next_char

输出

string 4 ['['RP0', 'LC0']] [3, 4] [3, '4']
© www.soinside.com 2019 - 2024. All rights reserved.