[英]How to convert a string to a Python array?
我有一个字符串如下所示:
"[3 3 3 3 4 3 4 ...]"
我需要将其转换为python
数组。 在做任何事情之前,我应该在每个数字之后添加,
吗? 或者
这可能吗? 如果有怎么办?
这是你想要的吗?
dd = "[3 3 3 3 4 3 4]"
new_dd = dd.replace('[','').replace(']','').split(' ')
# ['3', '3', '3', '3', '4', '3', '4']
# if you want to convert int.
[int(d) for d in new_dd]
# [3, 3, 3, 3, 4, 3, 4]
是的,您可以使用.split() function。 只需这样做:
string = "..." # The string here
numbers = string[1:-1].split() # We have the 1:-1 here because we want to get rid of the square brackets that are in the string.
但是如果你想要一个整数列表(int)而不是一个字符串数组,那么你需要:
s = "[3 3 4 3 4]"
numbers = s[1:-1].split() # a list of strings
print(numbers)
numbers = [int(n) for n in numbers] # a list of integers
print(numbers)
印刷:
['3', '3', '4', '3', '4']
[3, 3, 4, 3, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.