2011-11-20 99 views
1
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" 

我需要找到上面字符串中的大写字符的索引号,并获得索引号的列表(或其他)以便再次使用该字符串,以相同索引号返回大写字符。查找字符串中的大写字符的索引号

也许我可以解决它的重新模块,但我没有找到任何选项让我回到索引号。 希望它可以理解,我已经做了一个研究,但无法找到解决办法。 谢谢。

顺便说一句,我使用的Python 3.X

回答

2

你可以沿着这条线的东西,只需要修改一点点,并收集这些位置开始到数组等:

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

@PeterPeiGuo:你甚至可以做'pattern_search = re.compile(...).search'并直接调用'pattern_search(s,start + 1)'。这使得代码运行得更快(如果这很重要)。 – EOL

1
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 

表示:

heLLo hOw are you toDay 
olLEh wOh era uoy yaDot