Reputation: 57
I want to write a program which takes a string as input and print a new copy of the string that has been correctly capitalized. My function should:
● Capitalize the first letter in the string
● Capitalize the first letter after a full-stop, exclamation mark or question mark
● Capitalize the word “i” if it is in lowercase.
Sample Input: my favourite animal is a dog. a dog has sharp teeth so that it can eat flesh very easily. do you know my pet dog’s name? i love my pet very much.
Sample Output: My favourite animal is a dog. A dog has sharp teeth so that it can eat flesh very easily. Do you know my pet dog’s name? I love my pet very much.
My code:
s = ('my favourite animal is a dog. a dog has sharp teeth so that it can eat flesh very easily. do you know my pet dog’s name? i love my pet very much.')
output = ''
count = 0
fl = 0
for i in s:
if count == 0:
output += i.upper()
count += 1
elif i == ' ':
output += i
elif i == '.' or '!' or '?':
output += i
fl = 1
elif fl == 1:
output += i.upper()
fl = 0
else:
output += i
print(output)
Upvotes: 1
Views: 129
Reputation: 1496
Your third elif
condition has a mistake,
You have done :
elif i == '.' or '!' or '?':
This means that '!' or '?'
is being computed everytime, which always results to True
and never reaches the next required elif fl == 1:
condition which handles the upper()
logic.
The correct elif
condition would be :
elif i == '.' or i == '!' or i == '?':
(Edit) for a single 'i' in the string, you'll need to implement a lookahead, I have changed the code below.
The corrected code :
s = ('my favourite animal is a dog. a dog has sharp teeth so that it can eat flesh very easily. do you know my pet dog’s name? i love my pet i very much. i')
output = ''
count = 0
fl = 0
for i in range(len(s)):
if count == 0:
output += s[i].upper()
count += 1
elif s[i] == 'i':
# handle end of string for the lookahead below
if i == len(s)-1:
output += s[i].upper()
elif s[i+1] == ' ':
output += s[i].upper()
elif s[i] == ' ':
output += s[i]
elif s[i] == '.' or s[i] == '!' or s[i] == '?':
output += s[i]
fl = 1
elif fl == 1:
output += s[i].upper()
fl = 0
else:
output += s[i]
print(output)
Upvotes: 1