Umer Arif
Umer Arif

Reputation: 255

Transforming list of (characters+numbers) into simple string in python. How?

I am making a python program in which i have to list consist of characters and numbers and i have to concatenate these characters and numbers to make a string e.g ['s','m','a','r','t','1','2','3'] should be smart123. It is not working it gives me error of type but I am confused about where is the type error. There is same list type . I am using **for** loop for this. My code is:

list = ['s','m','a','r','t',1,2,3]
s = ""
for i in list:
    s += i
print(s)

Upvotes: 1

Views: 111

Answers (3)

Nipun Bhalla
Nipun Bhalla

Reputation: 54

For resolving your type error:

list=['s','m','a','r','t',1,2,3]
s="" 
for i in list: 
    s+=str(i)
    print(s)

You get type error because you are appending a number to a string. So first, you need to convert number into str and then append it.

Additionally, you can skip for loop and try ''.join()

list = ['s','m','a','r','t',1, 2, 3] 
s = ''.join([str(i) for i in list])

Lastly, list is a special keyword in python so never use only list as name for a list.

Upvotes: 2

Vlad
Vlad

Reputation: 8595

Use join():

list_ = ['s','m','a','r','t',1,2,3]
joined = ''.join([str(x) for x in list_])
print(joined)
# smart123

Upvotes: 3

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

You can simply use join() method :

list=['s','m','a','r','t',1,2,3]
s = "".join([str(k) for k in list])

OUTPUT :

s = 'smart123'

NOTE : A pythonic way would be not to assign any variable name as list.

Upvotes: 2

Related Questions