Capitalizing letters using for in range loop

107 views Asked by At

I'm trying to solve a problem where a for in range loop goes over a sentence and capitalises every letter following a ".", a "!" and a "?" as well as the first letter of the sentence. For example,

welcome! how are you? all the best!

would become

Welcome! How are you? All the best!

i've tried using the len function, but I'm struggling with how to go from identifying the placement of the value to capitalising the next letter.

2

There are 2 answers

0
Caridorc On

I will give you two hints:

>>> 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')]

These two functions will greatly help you in solving this problem.

0
flakes On

I would do this with a regex substitution using a callable. There are two cases for the substitution.

  • The string starts with a lower: ^[a-z]
  • There is a ., ! or ? followed by space and a lower. [.!?]\s+[a-z]

In both cases you can just uppercase the contents of the match. Here's an example:

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)

This results in:

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