简体   繁体   English

如何使用Python将字符串中的特定字符序列转换为大写?

[英]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.

相关问题 如何在不使用python中的字符串函数的情况下将字符串的字符从小写转换为大写,反之亦然? - How to convert characters of a string from lowercase to upper case and vice versa without using string functions in python? 使用python将字符串中的特定单词转换为大写或小写 - Specific words in a string to upper case or lowercase using python 如何在Python中检查字符是否为大写? - How to check if a character is upper-case in Python? 在 python 中转换为大写 - convert to upper case in python How to convert a unicode string to upper/lower/title case using Python's C API avoiding functions deprecated in Python 3.3? - How to convert a unicode string to upper/lower/title case using Python's C API avoiding functions deprecated in Python 3.3? 如果是大写,如何转换为小写字符串 - How to convert to lower case string if it's in upper case 将带有转义序列的字符串转换为python中的原始字符表示形式 - Convert a string with escape sequences to their original character representation in python 只有在python中后跟特定字符串时才更改大写 - change the upper case only if followed by specific string in python 仅在 python 字符串/列表中的特定字符上大写 - Upper case only on specific characters in python string/list 如何使用Python转换字符串中的每个字符 - How to Convert Each Character in a String using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM