Christopher
Christopher

Reputation: 23

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

there is too much code to put here so i'll just show where the problem is happening:

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

Upvotes: 0

Views: 274

Answers (1)

Sekar Ramu
Sekar Ramu

Reputation: 483

With ''.join(list) it should work.

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

If list of lists needs to be joined then use below format

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

and if you want to combine the list of list with the variables then see below

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

if your list has numeric values then you will have to convert those to string before trying to concatenate, else exception will be thrown like below.

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

Upvotes: 1

Related Questions