简体   繁体   中英

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]'. In this case the result of the conversion would be '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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM