【问题标题】:find index number of uppercase character in a string查找字符串中大写字符的索引号
【发布时间】:2011-11-20 21:03:47
【问题描述】:
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

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以沿着这条线做一些事情,只需要稍微修改它并将这些起始位置收集到一个数组等中:

    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)
    

    【讨论】:

    • @PeterPeiGuo:你甚至可以做pattern_search = re.compile(…).search,直接拨打pattern_search(s, start+1)。这使代码运行得更快(如果这很重要的话)。
    • 为什么pattern_search = re.compile(…).searchpattern_search(s, start+1) 让代码更快(在很大程度上)?
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 2020-10-24
      • 2019-11-12
      • 2012-05-29
      • 1970-01-01
      相关资源
      最近更新 更多