codewin
codewin

Reputation: 41

How to change the type of all elements to a single type(from int to str)?

I have a list a=['1','2',3,4,5,6] How do i get the list a=['1','2','3','4','5','6']?

I have tried using str. but doesn't work my try out

Upvotes: 0

Views: 867

Answers (6)

sahasrara62
sahasrara62

Reputation: 11228

a=['1','2',3,4,5,6]
a=[str(a[i]) for i in range(len(a))]

output

['1', '2', '3', '4', '5', '6']

Upvotes: 1

dodopy
dodopy

Reputation: 169

your code is ok, but str is a build-in function, you may have renamed str to some value, this will got a err.

>>> str = 'str'
>>> str('1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Upvotes: 1

Vinu Chandran
Vinu Chandran

Reputation: 325

You need to take each element and convert it into string. Converting the whole list at once(like a=str(a) ), won't work.

for idx, element in enumerate(a):
    a[idx] = str(element)

Upvotes: 1

Anonymous
Anonymous

Reputation: 699

2nd Approach:

import numpy as np
a= np.array(a,dtype=str)

Upvotes: 1

guest12345
guest12345

Reputation: 11

List comprehension:

a = [str(x) for x in a]

Map:

a = list(map(str, a))

Upvotes: 1

amine456
amine456

Reputation: 126

You can use a list comprehension:

a=[str(elt) for elt in a]

Upvotes: 6

Related Questions