如何将用引号引起来的逗号分隔的字符串转换为带有分隔元素的列表

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

我正在尝试将用逗号(,)分隔并括在单引号('')中的字符串转换为列表,并且该列表必须将其作为单独的元素。以下是字符串

String_tobe_Tested = " 'hello', 'Ruper's', 'how am i and', 'are','you'"

[如果仔细观察字符串,则会发现单词和开头或逗号之间有空格,例如, 'Ruper's'

因此,当我将其转换为列表时,它的长度为2而不是5。 2,因为最后一个单词“ you”中没有空格。

我想将其正确转换为一个包含每个元素的列表,即如果[]内的句子与'how are you doing,and how am I'之间必须存在,则必须按原样将其分隔开,即'您怎么样了,怎么样?我应该是一个要素。以下是我的代码。

 String_tobe_Tested = String_tobe_Tested.strip('"')
#String_tobe_Tested = eval(String_tobe_Tested)
String_tobe_Tested = String_tobe_Tested.split("','")
print(len(String_tobe_Tested))

有人可以帮助我吗?谢谢:)

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

您为什么不尝试这样的事情?

import re

String_tobe_Tested = " 'hello', 'Ruper's', 'how am i and', 'are','you'"
String_tobe_Tested = String_tobe_Tested[2:-1]
print(String_tobe_Tested)
String_tobe_Tested = String_tobe_Tested.strip('"')
#String_tobe_Tested = eval(String_tobe_Tested)
#String_tobe_Tested = String_tobe_Tested.split("','")
String_tobe_Tested = re.compile("','|', '").split(String_tobe_Tested)
print(String_tobe_Tested)
print(len(String_tobe_Tested))
© www.soinside.com 2019 - 2024. All rights reserved.