如何在不更改类型的情况下在列表中添加字符串元素?

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

我有一个包含 strint 的字符串,例如 string = "qA2"。我想在列表中添加 'q''A'2,但我不想更改元素的类型。可能吗?

您可以使用 str class 的 .isdigit() 方法来执行以下操作:

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

请注意,对于 "x²" 这样的字符串,这将失败,因为 ²(上标 2)出于某种原因被 .isdigit() 方法视为数字。以下比较安全:

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