如何使用Python将字符串中特定字符序列转换为大写?
我想实现一个功能,想问问大家有没有好的建议。
我有一个字符串,比如说'this-is,-toronto.-and-this-is,-boston',我想把里面所有的',-[小写字母]'转换成',-[大写字母]'。这样转换后,结果应该是'this-is,-Toronto.-and-this-is,-Boston'。
我一直在尝试用re.sub()来实现这个功能,但到现在还没找到合适的方法。
testString = 'this-is,-toronto.-and-this-is,-boston'
re.sub(r',_([a-z])', r',_??', testString)
谢谢大家!
1 个回答
11
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
打印输出
this-is,-Toronto.-and-this-is,-Boston