Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add elements of a string in a list without changing their types?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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', '²']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading