Type specific characters in a string and capitalize them

Asked 2 years ago, Updated 2 years ago, 42 views

InputStr=input('Input a sentence :')
Inputfind=input('Input a word for search :')
findLength=len(Inputfind)

Index=InputStr.find(Inputfind)



if Index==-1:
    print('There are no characters to replace.')
else:
    beforeStr=InputStr[0:Index]
    changeStr=InputStr[Index:Index+findLength].upper()
    afterStr=InputStr[Index+findLength:]
    result=beforeStr+changeStr+afterStr
    print(result)
    print('A word "',Inputfind,'" apperas',InputStr.count(Inputfind),'times in the sentence.')

If you follow the code above, only the first word is changed to capital letters, and then it cannot be executed after that,

ex) If you enter power overwelming, it says power overwelming.

I want to make it come out as POWER OVER WHELMING, so how can I fix it?

python string

2022-09-21 17:37

1 Answers

Str's find method is a method that receives a string, a start index, and an end index as an argument and returns the first location where the string is found.

Therefore, the above source will only convert the first string found because it returns only the first position where the string you want to find in the input string matches.

There are two ways to fix the source above so that you get the desired result.

InputStr=input('Input a sentence :')
Inputfind=input('Input a word for search :')
indexes = []
start, end = 0, len(InputStr)
while True:
    index = InputStr.find(Inputfind, start, end)
    if index == -1:
        break
    indexes.append(index)
    start = index+len(Inputfind)
InputStr = list(InputStr)
for i in indexes:
    InputStr[i:i+len(Inputfind)] = list(Inputfind.upper())

if not indexes:
    print('There are no characters to replace.')
else:
    print(''.join(InputStr))
    print('A word "',Inputfind,'" apperas', len(indexes),'times in the sentence.')
InputStr=input('Input Sentence :')
Inputfind=input('Input a word for search :')
findLength=len(Inputfind)
Index=InputStr.find(Inputfind)

    if Index==-1:
        print('There are no characters to replace.')
    else:
        result = InputStr.replace(Inputfind, Inputfind.upper())
        print(result)
        print('A word "',Inputfind,'" apperas',InputStr.count(Inputfind),'times in the sentence.')


2022-09-21 17:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.