简体   繁体   English

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

[英]How to convert a string with spaces to list in python

I want to convert a string to a list.我想将字符串转换为列表。

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' ]

Desired Result :预期结果:

#Output : [ namenamelocation]

Basically I do not want the list to get separated after spaces and want the term string to be a single index in list.基本上我不希望列表在空格后分开,并且希望术语字符串是列表中的单个索引。

# remove spaces and then put into list
[string.replace(" ", "")]

To add, if you don't add the spaces at the beginning, you don't need to use .replace() , just the brackets []补充一下,如果开头不加空格,则不需要使用.replace() ,只需要括号[]

string = [fName + lName + location]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM