hak*_*121 1 python string list type-conversion python-3.x
我想做什么:
获取一个字符串并附加该字符串的向后副本,形成回文
我想出了什么:
# 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)
Run Code Online (Sandbox Code Playgroud)
问题:当运行时,该脚本接受一个字符串,例如“test”,并返回['t', 'e', 's', 't', 't', 's', 'e', 't'];我对这个结果感到困惑,因为我将和c串联的结果显式转换为字符串。( ) 我知道我一定错过了一些基本的东西,但我无法弄清楚是什么。有人可以解释一下吗?谢谢你!abc = str(c)
有人愿意详细说明为什么我的c = str(c)不起作用吗?谢谢!
这种说法的问题c = str(c)在于,应用于str列表只是给出了该列表的字符串表示形式- 例如,str([1,2,3])产生了 string '[1, 2, 3]'。
将字符串列表放入字符串的最简单方法是使用str.join()方法。给定一个字符串s和一个a字符串列表,运行s.join(a)返回一个通过连接 的元素形成的字符串a,使用s作为粘合剂。
例如:
a = ['h','e','l','l','o']
print( ''.join(a) ) # Prints: hello
Run Code Online (Sandbox Code Playgroud)
或者:
a = ['Hello', 'and', 'welcome']
print( ' '.join(a) ) # Prints: Hello and welcome
Run Code Online (Sandbox Code Playgroud)
最后:
a = ['555','414','2799']
print( '-'.join(a) ) # Prints: 555-414-2799
Run Code Online (Sandbox Code Playgroud)