Skip to main content
 首页 » 编程设计

Python-无法将列表转换为字符串

2025年05月04日21zhenyulu

我试图做的事情:

Take a string and append a backwards copy of that string, making a palindrome

我想出了什么:

# take an input string 
a = input('Please enter a string: ') 
a = list(a) 
 
# read the string backwards 
b = list(reversed(a)) 
 
# append the backward-ordered string to the original string, and print this new string 
c = a + b 
c = str(c) 
 
print(c) 

问题:运行时,此脚本接受一个字符串,例如“test”,并返回 ['t', 'e', 's', 't' , 't', 's', 'e', 't'];我对这个结果感到困惑,因为我明确地将 c 转换为字符串,这是 a 和 b 连接的结果。 (c = str(c)) 我知道我一定在这里错过了一些基本的东西,但我无法弄清楚是什么。有人可以对此有所了解吗?谢谢你!

并且有人愿意详细说明为什么我的c = str(c) 不起作用吗?谢谢!

请您参考如下方法:

说 c = str(c) 的问题在于,将 str 应用于列表只会给出该列表的字符串表示 -因此,例如,str([1,2,3]) 生成字符串 '[1, 2, 3]'。

将字符串列表放入字符串中的最简单方法是使用 str.join() 方法。给定一个字符串 s 和一个字符串列表 a,运行 s.join(a) 返回一个通过连接 的元素形成的字符串>a,使用 s 作为胶水。

例如:

a = ['h','e','l','l','o'] 
print( ''.join(a) ) # Prints: hello 

或者:

a = ['Hello', 'and', 'welcome'] 
print( ' '.join(a) ) # Prints: Hello and welcome 

最后:

a = ['555','414','2799'] 
print( '-'.join(a) ) # Prints: 555-414-2799