0

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(''.join(str(x)))

But it gives me an error that says:

print(''.join(str(x)))
TypeError: 'str' object is not callable`

Guess it's occurring because of those integers along with the strings.

How to tackle this to get the desired output as mentioned above?

1
  • 2
    print(''.join(map(str, x))) Commented Apr 1, 2019 at 10:13

5 Answers 5

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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]))

Comments

0

Try this :

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

OUTPUT :

A2B2C2D2a4b2c1d2

Comments

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

For understanding:

s = ''                             # empty var
for elem in x:                     # for each elem in x
    s += str(elem)                 # concatenate it with prev s
print(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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.