【问题标题】:How to ignore capitalization BUT return same capitalization as input如何忽略大写但返回与输入相同的大写
【发布时间】:2023-03-15 03:27:01
【问题描述】:

我的代码打算识别第一个非重复字符串字符、空字符串、重复字符串(即abbaaa),但它也意味着在返回时将小写和大写输入视为相同的字符在它的原始大小写输入中准确的非重复字符。

def first_non_repeat(string):
    order = []
    counts = {}
    for x in string:
        if x in counts and x.islower() == True:
            counts[x] += 1
        else:
            counts[x] = 1 
            order.append(x)
    for x in order:
        if counts[x] == 1:
            return x
    return ''

我在第 5 行的逻辑是,如果我将所有字母输入设为小写,那么它将遍历字符串输入并且不区分大小写。但到目前为止,当我真的需要'T' 时,输入'sTreSS' 并输出's'。如果最后两个S 是小写的,那么它将是'T',但我需要足够灵活的代码来处理任何大小写输入。

【问题讨论】:

  • 重点是if x in counts 只会以区分大小写的方式查找x
  • 对,我希望该语句在查找 x 时忽略大小写
  • 有什么消息吗?我在下面发布了一个基于正则表达式的替代解决方案。

标签: python string case


【解决方案1】:

比较两个字母时,使用 lower() 比较字符串中的字符。一个例子是:

string ="aabcC"
count = 0
while count < len(string) - 1:
    if string[count].lower() == string[count + 1].lower():
        print "Characters " + string[count] + " and " + string[count + 1] + " are repeating."
    count += 1

【讨论】:

  • 这会被视为它自己的 for 循环吗?这将放在我的脚本中的什么位置?
  • @Mr.Jibz 我为你添加了一个更深入的例子
【解决方案2】:

您可以对代码进行一些小改动以使其正常工作。

 def first_non_repeat(string):
            order = []
            counts = {}
            for x in string:

                char_to_look = x.lower()   #### convert to lowercase for all operations

                if char_to_look in counts :
                    counts[char_to_look] += 1

                else:
                    counts[char_to_look] = 1 
                    order.append(char_to_look)

           for x in string:   ### search in the string instead or order, character and order will remain the same, except the case. So again do x.lower() to search in count
                if counts[x.lower()] == 1:
                    return x
            return ''1

【讨论】:

    【解决方案3】:

    重点是counts 中的x 以不区分大小写的方式进行搜索。你必须实现自己的不区分大小写的字典,或者使用正则表达式来检测重复的字母:

    import re
    def first_non_repeat(string):
        r = re.compile(r'([a-z])(?=.*\1)', re.I|re.S)
        m = r.search(string)
        while m:
            string = re.sub(m.group(1), '', string, re.I)
            m = r.search(string)
        return string[0]
    
    print(first_non_repeat('sTreSS'))
    

    Python demo

    ([a-z])(?=.*\1) 正则表达式查找任何也出现在前面某处的 ASCII 字母(请注意,([a-z]) 捕获 char 到第 1 组,(?=.*\1) 是一个前瞻,其中\1 匹配在与 .* 模式匹配的任何 0+ 个字符之后捕获到组 1 中的相同字符,re.S 标志有助于支持带换行符的字符串。

    re.sub 将以不区分大小写的方式删除所有找到的字母,因此我们只会在 while 块之后的 string 中获取唯一字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多