简体   繁体   中英

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))

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\b)', 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.

Another option using a regex is to narrow down the match for characters only to be uppercased using a negated character class [^\W_\d] to match word characters except a digit or underscore followed by matching a non whitespace characters

This will for example uppercase a) to A) but will not match 3 in 3d

Explanation

[^\W_\d](?=\S(?!\S))
  • [^\W_\d] Match a word char except _ or a digit
  • (?= Positive lookahead, assert what is directly to the right is
    • \S(?!\S) Match a non whitespace char followed by a whitespace boundary
  • ) Close lookahead

See a regex demo and a Python demo

Example

import re

regex = r"[^\W_\d](?=\S(?!\S))"
s = ("I Like Studying Python Programming\n\n"
    "a) This is a test with 3d\n")

output = re.sub(regex, lambda m: m.group(0).upper(), s)
print(output)

Output

I LiKe StudyiNg PythOn ProgrammiNg

A) ThIs Is a teSt wiTh 3d

Using the PyPi regex module , you could also use \p{Ll} to match a lowercase letter that has an uppercase variant.

\p{Ll}(?=\S(?!\S))

See a regex demo and a Python demo

Simple check whether the length of each word is greater than one, only then convert the second last letter to uppercase and append it to the variable result, if the length the word is one, append the word as it is to the result variable.

Here is the code:

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

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

print(" ".join(result))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM