2011-11-20 67 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