Home > Software design >  How to add elements of a string in a list without changing their types?
How to add elements of a string in a list without changing their types?

Time:12-13

I have a string which includes str and int, for example string = "qA2". I want to add 'q', 'A' and 2 in a list but I don't want to change the type of elements. Is it possible?

CodePudding user response:

You can use the .isdigit() method of the str class to do the following:

>>> s = "qA234"
>>> [int(x) if x.isdigit() else x for x in s]
['q', 'A', 2, 3, 4]

Note that this will fail for strings such as "x²" because ² (superscript 2) is considered a digit by the .isdigit() method for some reason. The following is safer:

>>> s = "3x²"
>>> [int(x) if "0" <= x <= "9" else x for x in s]
[3, 'x', '²']
  • Related