Python 将列表转换为字符串
我假设得到一个字符串Python 将列表转换为字符串,python,Python,我假设得到一个字符串'cs1010s',您可以使用它将非字符串元素转换为str,并连接字符串序列: to_str(['c', 's', 1, 0, 1, 0, 's']) 编辑: 因为您似乎希望使用递归来解决这个问题,所以(在本例中)使用迭代(while循环)是没有意义的 您必须显式强制转换到str,因为列表中的某些元素是int,并且不能使用+将str和int连接起来: def to_str(lst): return ''.join(map(str, lst)) 在连接之前,应将列
'cs1010s'
,您可以使用它将非字符串元素转换为str
,并连接字符串序列:
to_str(['c', 's', 1, 0, 1, 0, 's'])
编辑:
因为您似乎希望使用递归来解决这个问题,所以(在本例中)使用迭代(while循环)是没有意义的
您必须显式强制转换到str
,因为列表中的某些元素是int
,并且不能使用+
将str
和int
连接起来:
def to_str(lst):
return ''.join(map(str, lst))
在连接之前,应将列表元素转换为字符串。另外,当列表为空时,返回空字符串,而不是空列表
def to_str(lst):
if len(lst) == 0:
return '' # if length is 0, return an empty string, so you can concatenate it
result = str(lst[0]) + to_str(lst[1:]) # concatenate first element with the result of to_str(the rest of the list)
return result
print to_str(['c', 's', 1, 0, 1, 0, 's'])
# cs1010s
好的,但我想知道我的代码出了什么问题@Christian@user3398505+1你的问题是因为你想知道为什么你的代码不起作用,而只是为了完成你的任务…这是一个很好的答案。如果你运行
to_str([])
你会得到一个[]
。您想要''
。另外,您有一个while循环,但在第一次迭代时返回,所以这是不必要的。我想你想要str(lst[0])+到_str(lst[1:])
我得到了一个无法将'list'对象隐式转换为str的错误@Jaygood,所以我们只需一行就可以做到:将str(L[0])+返回到_str如果我还有',
@GrijeshChauhan是的,Python一行程序总是很好而且紧凑:)
def to_str(lst):
if len(lst) == 0:
return '' # if length is 0, return an empty string, so you can concatenate it
result = str(lst[0]) + to_str(lst[1:]) # concatenate first element with the result of to_str(the rest of the list)
return result
print to_str(['c', 's', 1, 0, 1, 0, 's'])
# cs1010s
def to_str(lst):
if len(lst) == 0:
return '' # return empty string
count = 0
while count <= len(lst):
# convert lst[count] to string before concatenating
result = str(lst[count]) + to_str(lst[1:])
count += 1
return result
def to_str(lst):
if not lst:
return ''
return str(lst[0]) + to_str(lst[1:])