Python 2.7 如何用str.split()将字符串变成函数外的列表?
Python 2.7 how to turn the string into a list outside the function with str.split()?
我写了一个函数把一个字符串 y 变成一个列表
但在函数完成后,字符串将保留为原始字符串。
我应该怎么做才能处理该对象,以便它在函数结束后成为一个列表?
我是编程新手,所以任何类型的输入都会很有帮助,非常感谢。
def str_to_list(x):
x = x.split(', ')
print x
return
y = "a, b, c, d, e"
str_to_list(y)
print y
您需要 return 您的结果,并将结果重新分配回 y
。您不能替换 y
绑定到的对象,否则字符串对象本身是不可变的:
def str_to_list(x):
x = x.split(', ')
return x
y = "a, b, c, d, e"
y = str_to_list(y)
print y
分割后的数组return需要
def str_to_list(x):
return x.split(', ')
print str_to_list("a, b, c, d, e")
所以你可以做到
def str_to_list(x):
return x.split(', ')
y = "a, b, c, d, e"
y = str_to_list(y)
print y
def str_to_list(x):
res = []
for i in range(len(x)):
res.append(x[i])
return res
比电话
y = str_to_list(y)
我写了一个函数把一个字符串 y 变成一个列表
但在函数完成后,字符串将保留为原始字符串。
我应该怎么做才能处理该对象,以便它在函数结束后成为一个列表?
我是编程新手,所以任何类型的输入都会很有帮助,非常感谢。
def str_to_list(x):
x = x.split(', ')
print x
return
y = "a, b, c, d, e"
str_to_list(y)
print y
您需要 return 您的结果,并将结果重新分配回 y
。您不能替换 y
绑定到的对象,否则字符串对象本身是不可变的:
def str_to_list(x):
x = x.split(', ')
return x
y = "a, b, c, d, e"
y = str_to_list(y)
print y
分割后的数组return需要
def str_to_list(x):
return x.split(', ')
print str_to_list("a, b, c, d, e")
所以你可以做到
def str_to_list(x):
return x.split(', ')
y = "a, b, c, d, e"
y = str_to_list(y)
print y
def str_to_list(x):
res = []
for i in range(len(x)):
res.append(x[i])
return res
比电话
y = str_to_list(y)