使用 for in range 循环将字母大写[关闭]

问题描述 投票:0回答:2

我正在尝试解决一个问题,其中 for in range 循环遍历一个句子并将“.”、“!”后面的每个字母大写和一个“?”以及句子的第一个字母。例如,

welcome! how are you? all the best!

会变成

Welcome! How are you? All the best!

我尝试过使用

len
函数,但我正在努力解决如何从识别值的位置到将下一个字母大写的问题。

python range for-in-loop capitalization
2个回答
1
投票

我会使用可调用的正则表达式替换来完成此操作。替换有两种情况。

  • 字符串以小写开头:
    ^[a-z]
  • 有一个
    .
    !
    ?
    ,后跟空格和下一个。
    [.!?]\s+[a-z]

在这两种情况下,您都可以将匹配的内容大写。这是一个例子:

import re

capatalize_re = re.compile(r"(^[a-z])|([.!?]\s+[a-z])")

def upper_match(m):
    return m.group(0).upper()

def capitalize(text):
    return capatalize_re.sub(upper_match, text)

这会导致:

>>> capitalize("welcome! how are you? all the best!")
Welcome! How are you? All the best!

0
投票

我给你两个提示:

>>> from itertools import tee
>>> def pairwise(iterable):
...     "s -> (s0,s1), (s1,s2), (s2, s3), ..."
...     a, b = tee(iterable)
...     next(b, None)
...     return zip(a, b)
... 
>>> list(pairwise([1,2,3,4,5,6]))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> list(enumerate("hello"))
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]

这两个函数将极大地帮助你解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.