1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
chonk1234
  • 11
  • 1
  • If `i` is the index of the punctuation character, `i+2` is the index of the start of the next sentence. Does that help? – Barmar Jan 23 '23 at 21:50
  • Welcome to Stack Overflow! [How to ask homework question](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) and [Open letter to students with homework problems](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) – Barmar Jan 23 '23 at 21:52
  • Does this answer your question? [How to capitalize the first letter of every sentence?](https://stackoverflow.com/questions/22800401/how-to-capitalize-the-first-letter-of-every-sentence) – Amin S Jan 23 '23 at 21:52
  • maybe, change character/letter to upper case if it comes after `' '` , `,`, `!`, `.` characters – sahasrara62 Jan 23 '23 at 21:55

2 Answers2

1

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!
flakes
  • 21,558
  • 8
  • 41
  • 88
0

welcome to StackOverflow, in order not to spoil the solution I will instead 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.

Caridorc
  • 6,222
  • 2
  • 31
  • 46