如何用大写字母替换字符串中的小写字母,也找不到替换

s.p*_*tra 1 python regex string

这是我的问题:我有一个字符串.然后我想用相应的大写字母替换小写字母,并且还想知道它必须为字符串做的替换次数.

S = "ABCdefGHijKLmNop"

Output string = "ABCDEFGHIJKLMNOP"
Run Code Online (Sandbox Code Playgroud)

和替换的数量.(在这种情况下为六)

然后我尝试使用re.sub:

New = re.sub("[a-z]","[A-Z]",S)
Run Code Online (Sandbox Code Playgroud)

但输出看起来像:

ABC[A-Z][A-Z][A-Z]GH[A-Z][A-Z]KL[A-Z]N[A-Z][A-Z]
Run Code Online (Sandbox Code Playgroud)

我也尝试使用字符串的替换功能,但是也没有用.

sty*_*ane 6

您可以使用.upper()以大写形式返回字符串的副本,并islower()使用sum()以获取替换的数量.

>>> S = "ABCdefGHijKLmNop"
>>> S.upper()
'ABCDEFGHIJKLMNOP'
>>> sum(1 for i in S if i.islower())
8
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用生成器函数和鲜为人知的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)
Run Code Online (Sandbox Code Playgroud)

表现如何?

%%timeit 
capitalize(S)
100000 loops, best of 3: 6.74 µs per loop
Run Code Online (Sandbox Code Playgroud)
%%timeit
S.upper()
sum(1 for i in S if i.islower())
100000 loops, best of 3: 3.12 µs per loop
Run Code Online (Sandbox Code Playgroud)
%%timeit
''.join(substitute(S))
it
100000 loops, best of 3: 6.9 µs per loop
Run Code Online (Sandbox Code Playgroud)