[英]How to convert a string with spaces to list in 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]
基本上我不希望列表在空格后分開,並且希望術語字符串是列表中的單個索引。
# remove spaces and then put into list
[string.replace(" ", "")]
補充一下,如果開頭不加空格,則不需要使用.replace()
,只需要括號[]
string = [fName + lName + location]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.