[英]How to convert specific character sequences in a string to upper case using Python?
I am looking to accomplish the following and am wondering if anyone has a suggestion as to how best go about it. 我希望完成以下内容,并且想知道是否有人建议如何最好地去做。
I have a string, say 'this-is,-toronto.-and-this-is,-boston', and I would like to convert all occurrences of ',-[az]' to ',-[AZ]'. 我有一个字符串,说'this-is,-toronto.-and-this-is,-boston',我想将所有出现的', - [az]'转换为', - [AZ]'。 In this case the result of the conversion would be 'this-is,-Toronto.-and-this-is,-Boston'. 在这种情况下,转换的结果将是'this-is,-Toronto.-and-this-is,-Boston'。
I've been trying to get something working with re.sub(), but as yet haven't figured out how how 我一直在尝试使用re.sub(),但尚未弄清楚如何使用
testString = 'this-is,-toronto.-and-this-is,-boston'
re.sub(r',_([a-z])', r',_??', testString)
Thanks! 谢谢!
re.sub can take a function which returns the replacement string: re.sub可以使用一个返回替换字符串的函数:
import re
s = 'this-is,-toronto.-and-this-is,-boston'
t = re.sub(',-[a-z]', lambda x: x.group(0).upper(), s)
print t
prints 版画
this-is,-Toronto.-and-this-is,-Boston
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.