在这种情况下,如何在Python中使用str.replace()?

2024-09-29 23:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

表达式示例:

"abcddomain_rgz.png"
"djhajhdomain_rgb1.png"

要将上述表达式中的domain*.png替换为"domain.json"

答复:

"abcddomain.json"
"djhajhdomain.json"

Tags: json示例png表达式domainrgb1abcddomainrgz
3条回答

改用python正则表达式(re package):

re.sub(r'domain.*\.png$', r"domain.json", 'djhajhdomain_rgb1.png')

这是注释部分提到的正则表达式的典型例子。由于在domain之后直到.png之前都不知道要替换的字符串的确切长度,因此需要使用正则表达式来执行替换

Python为您提供了^{}模块,您可以使用它的^{}函数执行替换:

import re

string = "djhajhdomain_rgb1.png"

result = re.sub("domain(.*).png", "domain.json", string)

print(result)

这将返回:

djhajhdomain.json

你最好的选择是正则表达式

x = "djhajhdomain_rgb1.png"
y = "djhajhdomain.json"

import re

pattern = re.compile(r'\w+domain')
ext = '.json'

match = re.match(pattern, x).group(0)
result = match+ext

assert result == y
  1. 导入正则表达式
  2. 编译一个模式以在字符串中搜索。(请注意,模式只接受文字字符串“domain”之前的字母数字和/或下划线)
  3. 设置预定义的字符串扩展名
  4. 使用编译的模式匹配字符串
  5. 连接结果
  6. 确认结果与所需输出匹配

相关问题 更多 >

    热门问题