Skip to main content
 首页 » 编程设计

python之如何用大写字母替换字符串中的小写字母并找出没有替换

2025年05月04日23mengfanrong

这是我的问题:我有一个字符串。然后我想用相应的大写字母替换小写字母,还想知道它必须对字符串进行的替换次数。

S = "ABCdefGHijKLmNop" 
 
Output string = "ABCDEFGHIJKLMNOP" 

和替换次数。(在本例中为六个)

然后我尝试使用 re.sub:

New = re.sub("[a-z]","[A-Z]",S) 

但输出看起来像:

ABC[A-Z][A-Z][A-Z]GH[A-Z][A-Z]KL[A-Z]N[A-Z][A-Z] 

我也试过sole,用string的replace函数也没有成功。

请您参考如下方法:

您可以使用 .upper()返回大写字符串的副本和 islower()与 sum()获取替换次数。

>>> S = "ABCdefGHijKLmNop" 
>>> S.upper() 
'ABCDEFGHIJKLMNOP' 
>>> sum(1 for i in S if i.islower()) 
8 

另一种方法是使用生成器函数和鲜为人知的 itertools.count类。

>>> from itertools import count 
>>> it = count(0) 
>>> def substitute(string): 
...     for char in string: 
...         if char.islower(): 
...             next(it) 
...             yield char.upper() 
...         else: 
...             yield char 
...  
>>> ''.join(substitute(S)) 
'ABCDEFGHIJKLMNOP' 
>>> it 
count(8) 

表现如何?

%%timeit  
capitalize(S) 
100000 loops, best of 3: 6.74 µs per loop 

%%timeit 
S.upper() 
sum(1 for i in S if i.islower()) 
100000 loops, best of 3: 3.12 µs per loop 

%%timeit 
''.join(substitute(S)) 
it 
100000 loops, best of 3: 6.9 µs per loop