【问题标题】:Python 2: substitution of chars in a stringPython 2:替换字符串中的字符
【发布时间】:2016-08-03 14:39:48
【问题描述】:

我需要将字符串转换为新字符串:如果该字符在原始字符串中仅出现一次,则新字符串中的每个字符必须为 '(',如果该字符在原始字符串中多次出现,则必须为 ')'细绳。 请你帮助我好吗?

myword = "attachment"

def duplicate_encode(word):
    from collections import Counter
    lst = list(word)
    counts = Counter(lst)
    newwrd = ""
        for key, value in counts.iteritems():
            if value > 1:
                newwrd += key.replace(key, ")")
            else: 
                newwrd += key.replace(key, "(")
        return newwrd

print duplicate_encode(myword)

我的输出:)((((())

预期输出))))((((())

编辑:如果是大写,我不想考虑它们(即“Fanfare”=>“))())((”)

【问题讨论】:

  • 您没有替换原始字符串中的字符;您正在替换 Counter 的键。它们不会以相同的顺序结束。
  • 完全删除newwrd,每次都在word上调用replace。也不需要将其转换为列表。

标签: python arrays string python-2.7 loops


【解决方案1】:

好的,解决了,感谢 Tamas(在他的大写问题解决方案中添加了 word.lower),感谢大家的帮助!

def duplicate_encode(word):
    from collections import Counter
    nwrd = word.lower()
    counter = Counter(nwrd)
    return "".join(")" if counter[c] > 1 else "(" for c in nwrd)

【讨论】:

    【解决方案2】:

    使用str.join 映射字符串中的所有字符:

    from collections import Counter
    def duplicate_encode(word):
      counter = Counter(word)
      return "".join(")" if counter[c] > 1 else "(" for c in word)
    print duplicate_encode("attachment") # "))))((((()"
    

    【讨论】:

    • 您的解决方案还不错,但我需要在确定字符是否重复时忽略大写字母。例如“Success”=>“)())())”
    • 知道了,添加了一个新的 word.lower() 变量
    【解决方案3】:

    只需迭代 Counter 对象并将 count 等于 1 的那些字符替换为 ( 并将其他所有字符替换为 )

    >>> from collections import Counter
    >>> myword = "attachment"
    >>> def duplicate_encode(word):
    ...     ct = Counter(word)
    ...     for k, v in ct.items():
    ...         if v == 1:
    ...             word = word.replace(k, '(')
    ...         else:
    ...             word = word.replace(k, ')')
    ...     return word
    ... 
    >>> duplicate_encode(myword)
    '))))((((()'
    

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2022-01-22
      • 2017-04-13
      • 2019-01-30
      • 2015-01-01
      相关资源
      最近更新 更多