如何在Python中用括号替换文本?(How to replace text between parentheses in Python?)

编程入门 行业动态 更新时间:2024-10-12 01:24:54
如何在Python中用括号替换文本?(How to replace text between parentheses in Python?)

我有一个包含以下键值对的字典:d = {'Alice':'x','Bob':'y','Chloe':'z'}

我想用任何给定字符串中的常量(键)替换小写变量(值)。

例如,如果我的字符串是:

A(x)的B(Y)C(X,Z)

如何替换字符以获得结果字符串:

A(爱丽丝)B(鲍勃)C(爱丽丝,小克)

我应该使用正则表达式吗?

I have a dictionary containing the following key-value pairs: d={'Alice':'x','Bob':'y','Chloe':'z'}

I want to replace the lower case variables(values) by the constants(keys) in any given string.

For example, if my string is:

A(x)B(y)C(x,z)

how do I replace the characters in order to get a resultant string of :

A(Alice)B(Bob)C(Alice,Chloe)

Should I use regular expressions?

最满意答案

具有替换功能的re.sub()解决方案:

import re d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') for k in m.group().strip('()').split(','))), s) print(result)

输出:

A(Alice)B(Bob)C(Alice,Chloe)

扩大的视野:

import re def repl(m): val = m.group().strip('()') d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) if ',' in val: return '({})'.format(','.join(flipped.get(k,'') for k in val.split(','))) else: return '({})'.format(flipped.get(val,'')) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', repl, s) print(result)

特定输入案例A(x)B(y)C(Alice,z) 奖励方法:

... s = 'A(x)B(y)C(Alice,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') or k for k in m.group().strip('()').split(','))), s) print(result)

re.sub() solution with replacement function:

import re d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') for k in m.group().strip('()').split(','))), s) print(result)

The output:

A(Alice)B(Bob)C(Alice,Chloe)

Extended version:

import re def repl(m): val = m.group().strip('()') d = {'Alice':'x','Bob':'y','Chloe':'z'} flipped = dict(zip(d.values(), d.keys())) if ',' in val: return '({})'.format(','.join(flipped.get(k,'') for k in val.split(','))) else: return '({})'.format(flipped.get(val,'')) s = 'A(x)B(y)C(x,z)' result = re.sub(r'\([^()]+\)', repl, s) print(result)

Bonus approach for particular input case A(x)B(y)C(Alice,z):

... s = 'A(x)B(y)C(Alice,z)' result = re.sub(r'\([^()]+\)', lambda m: '({})'.format(','.join(flipped.get(k,'') or k for k in m.group().strip('()').split(','))), s) print(result)

更多推荐

本文发布于:2023-08-07 16:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465344.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   中用   文本   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!