英文:
Substitute a part of string (ignoring special characters)
问题
假设我有一个字符串列表,并想使用 re.sub
来替换其中的不同部分。我的问题是有时这种替换包含特殊字符,因此该函数无法正确匹配结构。一个例子:
import re
txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'
re.sub('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd', txt)
这里的问题出在 (
和 )
,但可能存在其他我现在不知道的形式。因此,我想完全忽略这些特殊字符并用我想要的字符串替换它们。在这种情况下,意味着:
'PC (Pty) Ltd, formerly known as apple shop Ltd., is a full-service firm which is engaged in the sale and servicing of motor vehicles.'
英文:
Suppose that I have a list of strings, and I want to substitute different parts of it by re.sub
. My problem is that sometimes this substitution contains special characters inside so this function can't properly match the structure. One example:
import re
txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'
re.sub('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd', txt)
Here the issue is coming from (
and )
, but the other forms may happen that I'm not aware of it now. So I want to totally ignore these special characters inside and replace them with my preferred strings. In this case, it means:
'PC (Pty) Ltd, formerly known as apple shop Ltd., is a full-service firm which is engaged in the sale and servicing of motor vehicles.'
答案1
得分: 1
If no special functionality of regular expressions is needed, this can be done easier with the str.replace method:
txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'
result = txt.replace('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd')
英文:
If no special functionality of regular expressions is needed, this can be done easier with the str.replace method:
txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'
result = txt.replace('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论