簡體   English   中英

如何將由變量組成的列表加入字符串(python [3.6.2])

[英]How do i join a list made of variables into a string (python[3.6.2])

這里有太多代碼,所以我只顯示問題出在哪里:

date = [day,month,year,time]
entrylist = [name,guess,date,email,phone]
entry = ''.join(entrylist)
print(entry)

使用''.join(list)應該可以工作。

>>> entrylist = ['name','guess','date','email','phone']
>>> entry = ''.join(entrylist)
>>> print(entry)
nameguessdateemailphone
>>> entry = ' '.join(entrylist)
>>> print(entry)
name guess date email phone
>>>

如果列表列表需要加入,請使用以下格式

>>> a = [[1, 2, "sekar"],[3, "hello", "stack"],["overflow" ,4, "hi"]]
>>> ''.join(str(r) for v in a for r in v)
'12sekar3hellostackoverflow4hi'
>>> ' '.join(str(r) for v in a for r in v)
'1 2 sekar 3 hello stack overflow 4 hi'
>>>

如果您想將列表列表與變量結合起來,請參見下文

>>> a = ['stack']
>>> b = ['over']
>>> c = ['flow']
>>> finallist = a + b + c
>>> ''.join(finallist)
'stackoverflow'

如果列表中包含數值,則必須先將其轉換為字符串,然后再進行連接,否則將引發異常,如下所示。

>>> a = [1, 2, "sekar"]
>>> b = [3, "hello", "stack"]
>>> c = ["overflow" ,4, "hi"]
>>> finallist = a + b + c
>>> " ".join(x for x in finallist)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>> " ".join(str(x) for x in finallist)
'1 2 sekar 3 hello stack overflow 4 hi'
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM