简体   繁体   English

Python 2:字符串中的字符替换

[英]Python 2: substitution of chars in a string

I need to convert a string into a new string: Each character in the new string must be '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. 我需要将字符串转换为新字符串:新字符串中的每个字符必须为'(',如果该字符在原始字符串中仅出现一次,则为')',如果该字符在原始字符串中出现多次。 Could you please help me? 请你帮助我好吗?

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)

My output: )((((() 我的输出:)(((((()

Output expected ))))((((() 预期输出))))((((((

Edit: in case of upper cases, I do not want to consider them (IE "Fanfare" => "))())((" ) 编辑:在大写的情况下,我不想考虑它们(即“ Fanfare” =>“))())((”)

Just iterate Counter object and replace those characters where count equals 1 by ( and everything else by ) 只需对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)
'))))((((()'

Using str.join to map all the characters in a string: 使用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") # "))))((((()"

Ok, solved, thanks to Tamas (added word.lower to his solution for the uppercase problem) and thank you all for your help! 好的,谢谢Tamas(在大写问题的解决方案下方添加了word.low),感谢大家的帮助!

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM