2

I have string that needs to be capitalized after "!":

I have made a script that works to a certain extent but gives me a problem when the last letter is "!".

strin "hello! there!" 

strout = []

for i in range(len(strin)):     
    if strin[i-2] == '!':
        strout.append((strin[i]).capitalize())

    else:
        strout.append(strin[i])
    strout[0] = strout[0].capitalize()

newStr = "".join(strout)

Output is: HEllo! There!


What can I do to prevent the second letter to be capitalized.
The reason for [i-2] is whenever the loop encounters a '!' in the middle of text it capitalizes the letter i.

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38

4 Answers4

5

What about this:

string = "hello! there!"
'! '.join(map(lambda s: s.lstrip().capitalize(), string.split('!')))
Cedric H.
  • 7,980
  • 10
  • 55
  • 82
2

a simple solution would be to capitalize only if i-2 >= 0.

try this:

strin = "hello! there!"

strout = []

for i in range(len(strin)):
    if i-2>=0 and strin[i-2] == '!':
        strout.append((strin[i]).capitalize())
    else:
        strout.append(strin[i])
strout[0] = strout[0].capitalize()

newStr = "".join(strout)

print(newStr)
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
2

If i is zero or one, then i-2 will map on -2 and -1 respectively. In Python -1 means the last element. So it will capitalize the E as you noticed.

It might make more sense to start at index 2:

strin = "hello! there!" 

strout = list(strin[:2])
for i in range(2, len(strin)):
    if strin[i-2] == '!':
        strout.append(strin[i].capitalize())
    else:
        strout.append(strin[i])
strout[0] = strout[0].capitalize()
result = ''.join(strout)

That being said, using a regular expression is probably more declarative here:

from re import compile as recompile

rgx = recompile(r'(?:[!]\s*|^)[a-z]')

outp = rgx.sub(lambda m: m.group(0).upper(), strin)

This will capitalize the first character, as well as all characters following an exclamation mark, regardless of the number of spaces in between.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

I used lstrip() in case there was a space or spaces preceding the character that you want to capitalize.

string = 'Hello! world'

capitalize = string.split('!')[1].lstrip().capitalize()  # replace .capitalize() with .upper to cap all letters

print(capitalize)
probat
  • 1,422
  • 3
  • 17
  • 33