【问题标题】:How to replace all numbers in a string with custom string in python? [closed]如何用python中的自定义字符串替换字符串中的所有数字? [关闭]
【发布时间】:2020-01-10 16:45:13
【问题描述】:

我想用Mat(number)替换给定字符串中的所有数字。例如转换后的字符串A*256+B*12+C*256必须看起来像这样A*Mat(256)+B*Mat(12)+C*Mat(256)如何在python 3中执行此操作?强>.

【问题讨论】:

  • 您搜索了什么,找到了什么?你尝试过什么,它是如何失败的?
  • 请向我们展示你的尝试?

标签: python python-3.x string replace


【解决方案1】:

您可以将re.sub 与以下模式一起使用:

import re
s = 'A*256+B*12+C*256'

re.sub(r'(\d+)', r'Mat(\1)', s)
# 'A*Mat(256)+B*Mat(12)+C*Mat(256)'

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 2020-11-22
    • 1970-01-01
    • 2021-04-28
    • 2021-01-06
    • 2023-03-21
    • 2021-12-01
    • 2014-03-06
    • 1970-01-01
    相关资源
    最近更新 更多