[英]Trying to parse a string into a list in Python
So I have a string like so: 所以我有一个像这样的字符串:
pattern = "AAaa$$##"
I want to parse it into a list so it outputs letter by letter, but I can't do pattern.split("")
cause it gives an error. 我想将其解析为一个列表,以便按字母输出,但是我无法执行
pattern.split("")
导致错误。 Like this pattern.split()
wont work either, it will just give me back the same string but in a list instead. 像这个
pattern.split()
不起作用,它只会给我相同的字符串,但会在列表中。
I need it to give me a list like this: ["A", "A", "a", "a", "$", "$", "#", "#"]
我需要它给我这样的列表:
["A", "A", "a", "a", "$", "$", "#", "#"]
Thanks in advance. 提前致谢。
Just do 做就是了
list(pattern)
It creates a list. 它创建一个列表。 Save it to any variable and use it.
将其保存到任何变量并使用。 See the Python Docs entry.
请参阅Python Docs条目。
For instance, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]
Although, you can just iterate over the strings like so 虽然,您可以像这样遍历字符串
>>> for elem in testString:
# Do Something
Test- 测试-
>>> pattern = "AAaa$$##"
>>> list(pattern)
['A', 'A', 'a', 'a', '$', '$', '#', '#']
>>> pattern = 'AAaa$$##'
>>> list(pattern)
['A', 'A', 'a', 'a', '$', '$', '#', '#']
But if you just want to outputs the string letter by letter, there is no need to parse it into a list. 但是,如果您只想逐个字母地输出字符串,则无需将其解析为列表。 The string itself is a sequence.
字符串本身是一个序列。
>>> for letter in pattern:
... print letter
...
A
A
a
a
$
$
#
#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.