Reputation: 11
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.
Upvotes: 1
Views: 131
Reputation: 6661
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.
Upvotes: 0
Reputation: 23674
I would do this with a regex substitution using a callable. There are two cases for the substitution.
^[a-z]
.
, !
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!
Upvotes: 1