在python字符串替换中使用星号字符(*)作为小丑? [英] Using asterisk character (*) as joker in python string replacement?

查看:122
本文介绍了在python字符串替换中使用星号字符(*)作为小丑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 的初学者,目前正在苦苦挣扎:

I am a beginner in python an am currently struggling with something:

我想在单个字符串中进行一些更改.是否可以使用单个星号 (*) 作为几个字符的替代小丑?例如我有一个字符串:

I want to make a couple of changes in a single string. Is it possible to use a single asterisk sign (*), as a replacement-joker for a couple of characters? For example I have a string:

string1 = "The new year is about to become an old year"

我想用这个模式来查找:

And I want to use this pattern for finding:

find:
*year*year*

replace it with:
*century*one*

这将导致:

string1 = "The new century is about to become an old one"

意思是*"字符将替换年份"之间和之前的所有字符.和年"字.这可能吗?

Meaning "*" character will replace all those characters between, and before the "year" and "year" words. Is that possible?

推荐答案

研究 正则表达式.在你的情况下,你需要知道的主要事情是 . 匹配任何单个字符, .* 匹配零个或多个任何字符,括号用于分组,和反斜杠后跟一个数字形成反向引用(现有组的).

It will be worth your while to look into regular expressions. In your case, the main things you need to know are that . matches any single character, .* matches zero or more of any character, that parentheses are used for grouping, and backslash followed by a number form a backreference (of an existing group).

所以,要匹配 year,然后是任意的东西,然后是 year,请使用 year.*year.

So, to match year, followed by arbitrary stuff, followed by year again, use year.*year.

现在,要替换,请使用分组和反向引用:

Now, to substitute, use the grouping and backreference:

import re
string2 = re.sub('year(.*)year', r'century\1one', string1)

正则表达式的有效使用对于大多数初学者来说绝对不是显而易见的.有关温和介绍的一些建议,请参阅此问题:

Effective use of regular expressions is definitely not obvious to most beginners. For some suggestions on gentler introductions, see this question:

https://stackoverflow.com/questions/2717856/any-good-and-gentle-python-regexp-tutorials-out-there

这篇关于在python字符串替换中使用星号字符(*)作为小丑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆