简体   繁体   中英

find index number of uppercase character in a string

string = "heLLo hOw are you toDay"
results = string.find("[A-Z]") <----- Here is my problem
string.lower().translate(table) <--- Just for the example.
>>>string
"olleh woh era uoy yadot"
#here i need to make the characters that where uppercase, be uppercase again at the same index number.
>>>string
"olLEh wOh era uoy yaDot"

i am need to find the index number of the uppercase characters in the string above, and get a list (or whatever) with the index numbers in order to use again on the string, to bring back the uppercased characters at the same index number.

maybe i can solve it the the re module, but i didn't find it any option to give me back the index numbers. hope it understandable, i have done a research but couldn't find solution to it. Thanks.

BTW, i am using python 3.X

You can do something along this line, just need to modify it a little bit and collect those start positions into an array etc:

import re

s = "heLLo hOw are you toDay"
pattern = re.compile("[A-Z]")
start = -1
while True:
    m = pattern.search(s, start + 1) 
    if m == None:
        break
    start = m.start()
    print(start)
string = "heLLo hOw are you toDay"
capitals = set()
for index, char in enumerate(string):
    if char == char.upper():
        capitals.add(index)

string = "olleh woh era uoy yadot"
new_string = list(string)
for index, char in enumerate(string):
    if index in capitals:
        new_string[index] = char.upper()
string = "".join(new_string)

print "heLLo hOw are you toDay"
print string

which shows:

heLLo hOw are you toDay
olLEh wOh era uoy yaDot

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