Skip to content Skip to sidebar Skip to footer

Converting A List Of Integers And Strings To Purely A String

I have a list whose contents are: x = ['A', 2, 'B', 2, 'C', 2, 'D', 2, 'a', 4, 'b', 2, 'c', 1, 'd', 2] I want the output as: A2B2C2D2a4b2c1d2 I tried with the line: print(''.joi

Solution 1:

Use map():

''.join(map(str, x))

Code:

x = ['A', 2, 'B', 2, 'C', 2, 'D', 2, 'a', 4, 'b', 2, 'c', 1, 'd', 2]

print(''.join(map(str, x)))
# A2B2C2D2a4b2c1d2

Solution 2:

str(x) gives the string representation of x - it doesn't iterate over the values in x. Try this:

print(''.join([str(a) for a in x]))

Solution 3:

Try this :

print(''.join([str(k) for k in x]))

OUTPUT :

A2B2C2D2a4b2c1d2

Solution 4:

x = ['A', 2, 'B', 2, 'C', 2, 'D', 2, 'a', 4, 'b', 2, 'c', 1, 'd', 2]

For understanding:

s = ''# empty varfor elem in x:                     # for each elem in x
    s += str(elem)                 # concatenate it with prev sprint(s)                           # A2B2C2D2a4b2c1d2

Which can be shorten to:

print(''.join([str(elem) for elem in x]))  # A2B2C2D2a4b2c1d2

Using reduce:

print(reduce(lambda x,y:str(x)+str(y),x))   # A2B2C2D2a4b2c1d2

Solution 5:

It can also be done by making a new list where all the elements from x have been converted to strings:

x = ['A', 2, 'B', 2, 'C', 2, 'D', 2, 'a', 4, 'b', 2, 'c', 1, 'd', 2]

strings = []

for e in x:
    strings.append(str(e))

print(''.join(strings))

The above answers are much cleaner though.

Post a Comment for "Converting A List Of Integers And Strings To Purely A String"