感叹号后面的字母变大写

2024-05-06 06:35:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串需要在“!”之后大写:

我已经做了一个脚本,工作到一定程度,但给我一个问题,当最后一个字母是“!”。你知道吗

strin "hello! there!" 

strout = []

for i in range(len(strin)):     
    if strin[i-2] == '!':
        strout.append((strin[i]).capitalize())

    else:
        strout.append(strin[i])
    strout[0] = strout[0].capitalize()

newStr = "".join(strout)

输出是:你好!在那里!你知道吗


如何防止第二个字母大写。
[i-2]的原因是每当循环遇到“!”在文本中间,它将字母i大写。你知道吗


Tags: 字符串in脚本helloforlen字母range
3条回答

一个简单的解决方案是只有在i-2 >= 0的情况下才将其资本化。你知道吗

试试这个:

strin = "hello! there!"

strout = []

for i in range(len(strin)):
    if i-2>=0 and strin[i-2] == '!':
        strout.append((strin[i]).capitalize())
    else:
        strout.append(strin[i])
strout[0] = strout[0].capitalize()

newStr = "".join(strout)

print(newStr)

这个呢:

string = "hello! there!"
'! '.join(map(lambda s: s.lstrip().capitalize(), string.split('!')))

如果i是零或一,那么i-2将分别映射到-2-1。在Python中-1表示最后一个元素。所以它将大写E,正如您所注意到的。你知道吗

从索引2开始可能更有意义:

strin = "hello! there!" 

strout = list(strin[:2])
for i in range(2, len(strin)):
    if strin[i-2] == '!':
        strout.append(strin[i].capitalize())
    else:
        strout.append(strin[i])
strout[0] = strout[0].capitalize()
result = ''.join(strout)

也就是说,在这里使用正则表达式可能更具声明性:

from re import compile as recompile

rgx = recompile(r'(?:[!]\s*|^)[a-z]')

outp = rgx.sub(lambda m: m.group(0).upper(), strin)

这将大写第一个字符,以及感叹号后面的所有字符,而不管中间有多少空格。你知道吗

相关问题 更多 >