Python中的字符串或列表替换

时间:2010-07-01 18:52:02

标签: python string list substitution

我如何选择字符串:

("h1", "h2", "h3, "h4")

用数字1, 2, 3, 4代替这些值?

相应地,我将如何在列表中执行相同的操作呢?

2 个答案:

答案 0 :(得分:4)

 to_replace = ["h1","h2","h3","h4"]
 replaced = [ int(s.replace("h","")) for s in to_replace ]

如果这是你想要的。

目前尚不清楚;我假设您的输入不是字符串"(\"h1\", \"h2\", \"h3\", \"h4\")",而是字符串列表。

我不确定你的第二个问题是什么意思,因为它看起来与第一个问题相同。

我会相应地更新我的答案=)

答案 1 :(得分:2)

这将删除每个非数字字符(不仅是h):

>>> s = ["h1", "h2" , "h3" , "h4"]
>>> [int(filter(lambda c: c.isdigit(), x)) for x in s]
[1, 2, 3, 4]

>>> s = ["x1", "b2" , "c3" , "h4"]
>>> [int(filter(lambda c: c.isdigit(), x)) for x in s]
[1, 2, 3, 4]