如何使用 python 和 regulairexpressios 将所有数字替换为数字以外的东西?

问题描述 投票:0回答:1

示例

假设我们想要用换行符

0
替换所有整数或非负整数(
1
2
3
\n
...)。

我们该怎么做?

输入 输出
"1 apple 2 orange 3 kiwi"
"\n apple \n orange \n kiwi"
python regex string regexp-replace
1个回答
0
投票

以下是一些匆忙编写的丑陋代码,但完成了工作......

import re
# `re` is the regular expression library 

# `re.sub`
#     is an abbreviation derived from... 
# `regular_expression.substitute`

large_old_text = "1 apple 2 orange 3 kiwi"

old_small_text = "[0-9]"

new_small_text = "\n"

large_new_text = re.sub(
    old_small_text,
    new_small_text,
    large_old_text
)

print(repr(large_new_text))

这篇文章主要是为了帮助那些可以使用快速脚本而不是花 10 分钟来编写脚本的人节省时间。

希望,如果您使用 Google 或其他搜索引擎来查找...

如何替换一段文本中的所有数字。

...然后此帖子会显示在顶部附近的某个位置。

© www.soinside.com 2019 - 2024. All rights reserved.