繁体   English   中英

Python中的字符串或列表替换

[英]String or list substitution in Python

我将如何去弦:

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

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

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

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

如果这是您想要的。

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

我不确定第二个问题是什么意思,因为它似乎与第一个问题相同。

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

这将去除每个非数字字符(不仅是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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM