如何在python中将带空格的字符串转换为列表

2024-09-29 02:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将字符串转换为列表

fName = input("Enter your First Name: \n")
lName = input("Enter your Last Name: \n")
location = input("Enter your Location: \n")

string = fName + " " + lName + " " + location

print(string)
print("String coverted to list :",string.split())
# Output : String coverted to list : ['name', 'name', 'location']

print("String coverted to list :\n",list(string))
# Output: String coverted to list : ['n', 'a', 'm', 'e', ' ', 'n', 'a', 'm', 'e', 'l', 'o', 'c', 'a', 't', 'i', 'o', 'n' ]

预期结果:

#Output : [ namenamelocation]

基本上,我不希望列表在空格后分开,而是希望术语字符串成为列表中的单个索引


Tags: to字符串name列表inputoutputyourstring