某个字符后的小写字母?

2024-10-03 11:15:31 发布

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

我喜欢string.capwords()的一些行为方式,也喜欢.title()的一些行为方式,但不是一种。在

我需要缩写字母大写,.title()可以,但是string.capwords()不能,而且{}不在单引号后大写字母,所以我需要两者的组合。我想使用.title(),,然后我需要在撇号后面的单个字母小写,前提是它们之间没有空格。在

例如,下面是一个用户的输入:

string="it's e.t.!"

我想把它转换成:

^{pr2}$

.title()将大写“s”,而string.capwords()不会将“e.t.”大写。在


Tags: 用户stringtitle字母方式it大写字母空格
3条回答

可以使用正则表达式替换(请参见^{}):

>>> s = "it's e.t.!"
>>> import re
>>> re.sub(r"\b(?<!')[a-z]", lambda m: m.group().upper(), s)
"It's E.T.!"

[a-z]将匹配小写字母。但不是在'(?<!')-否定查找后断言)之后。并且字母应该出现在单词边界之后;因此t将不匹配。在

re.sublambda的第二个参数将返回替换字符串。(信的上部版本)并将用于替换。在

如果您不想使用regex,您可以始终使用这个简单的for循环

s = "it's e.t.!"
capital_s = ''
pos_quote = s.index("'")
for pos, alpha in enumerate(s):
    if pos not in [pos_quote-1, pos_quote+1]:
        alpha = alpha.upper()
    capital_s += alpha
print capital_s

希望这有帮助:)

a = ".".join( [word.capitalize() for word in "it's e.t.!".split(".")] )
b = " ".join( [word.capitalize() for word in a.split(" ")] )
print(b)

编辑后改为使用大写函数。现在它开始看起来像有用的东西了:)。但是这个解决方案不适用于其他空白字符。为此,我会同意费斯托鲁的解决方案。在

相关问题 更多 >