找到字符串中大写字母的索引位置
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"
我需要找到上面字符串中大写字母的索引位置,也就是它们在字符串中的位置,然后把这些位置的列表(或者其他形式)保存下来,以便再次使用,从而能够在相同的位置提取出大写字母。
也许我可以用re模块来解决这个问题,但我没有找到任何选项可以让我得到这些索引位置。希望这样说能让你明白,我做了一些研究,但还是找不到解决办法。
顺便说一下,我使用的是Python 3.X。
2 个回答
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
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)