How to change hybrid type list to str

Viewed 74

I have a hybird type list:

A=[0, '0,1', 0, '0,1', '0,1', '0,1', '0,1', 0]

want to change all to str, but I try

for i in A:
  if type(i) == int:
    str(i)
  print(type(i))

and get nothing change about those type

<class 'int'>
<class 'str'>
<class 'int'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
2 Answers

You need to overwrite the type in third line str(i) should be i = str(i),

A=[0, '0,1', 0, '0,1', '0,1', '0,1', '0,1', 0]

for i in A:
  if type(i) == int:
    i = str(i)
  print(type(i))


# output
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

Please note that this wouldn't change the type of original list. For that you need to overwrite the value in the list itself,

for i in range(len(A)):
  if type(A[i]) == int:
    A[i] = str(A[i])

chr is a function that returns a new single character str; if you don't assign the result, it's a no-op. So the simplest fix is:

for i, x in enumerate(A):  # enumerate to get indices so we can assign back
    if type(x) is int:     # Type checks use is, not == (or use isinstance)
        A[i] = x = chr(x)  # Reassign x as well if you want to use the new value
    print(type(x))

That said, it won't make the string '0', it's going to make the string '\x00', because chr converts based on raw Unicode ordinals (ASCII ordinals on Py2). If you wanted to produce '0', use str instead:

for i, x in enumerate(A):  # enumerate to get indices so we can assign back
    if type(x) is int:
        A[i] = x = str(x)
    print(type(x))
Related