Python 中的字符串或列表替换

发布于 2024-09-08 01:52:57 字数 141 浏览 7 评论 0原文

我将如何获取一个字符串:

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

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

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

How would I go about taking a string:

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

And substituting these values with numbers 1, 2, 3, 4?

Correspondingly, how I would I preform the same operation but on a list instead?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜柠檬 2024-09-15 01:52:57
 to_replace = ["h1","h2","h3","h4"]
 replaced = [ int(s.replace("h","")) for s in to_replace ]

如果这就是你想要的。

还不太清楚;我假设您的输入实际上不是一个字符串 "(\"h1\", \"h2\", \"h3\", \"h4\")",而是一个列表字符串。

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

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

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

If this is what you want.

It's not exactly clear; I'm assuming that your input is not literally a string "(\"h1\", \"h2\", \"h3\", \"h4\")", but a list of strings.

And I'm not sure what you meant by your second question, as it appears to be the same as the first.

I will update my answer accordingly =)

小ぇ时光︴ 2024-09-15 01:52:57

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

This would strip out every non-numeric character (not only h):

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

or

>>> s = ["x1", "b2" , "c3" , "h4"]
>>> [int(filter(lambda c: c.isdigit(), x)) for x in s]
[1, 2, 3, 4]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文