Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

string - how to change ith letter of a word in capital letter in python?

I want to change the second last letter of each word in capital letter. but when my sentence contains a word with one letter the program gives an error of (IndexError: string index out of range). Here is my code. It works with more than one letter words. if I write, for example, str="Python is best programming language" it will work because there is not any word with (one) letter.

str ="I Like Studying Python Programming"
array1=str.split()

result =[]
for i in array1:
     result.append(i[:-2].lower()+i[-2].upper()+i[-1].lower())

print(" ".join(result))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem is quite amenable to using regular expressions, so I would recommend that here:

str = " I Like Studying Python Programming"
output = re.sub(r'(w)(?=w)', lambda m: m.group(1).upper(), str)
print(output)

This prints:

I LiKe StudyiNg PythOn ProgrammiNg

Note that this approach will not target any single letter words, since they would not be following by another word character.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...