2009-05-27 31 views
2

我期待完成以下內容,並且想知道是否有人對如何實現最佳效果提出建議。如何使用Python將字符串中的特定字符序列轉換爲大寫?

我有一個字符串,說'this-is,-toronto.-and-this-is,-boston',並且我想將所有出現的', - [az]'轉換爲', - [ AZ]」。在這種情況下,轉換的結果將是「這是 - 多倫多 - 這是 - 波士頓」。

我一直在努力得到的東西與應用re.sub工作(),但至今還沒有想出如何如何

testString = 'this-is,-toronto.-and-this-is,-boston' 
re.sub(r',_([a-z])', r',_??', testString) 

謝謝!

回答

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 
+0

+1,打我吧:)礦匹配整個單詞,並呼籲x.group (0)。資本化,但你的工作原理相同,速度可能更快。 – dwc 2009-05-27 12:52:42

相關問題