如何对字符串中的字符进行排序,但只保留撇号

时间:2017-10-02 17:55:51

标签: python python-3.x

我似乎无法弄清楚如何对字符串中的字符进行排序但保留撇号。 这就是我到目前为止所做的:

def scramble_word(word) -> str:
    index = word.find("'")
    return word[0] + ''.join(sorted(word[1:index]+word[index+1:-1], key=str.lower)) + word[-1]


print(scramble_word("Mo'uSE"))  # -> Mo'SuE
print(scramble_word("qu'iz"))  # -> qi'uz

我得到的是MoSue和qiuz。如何将撇号插回字符串?

4 个答案:

答案 0 :(得分:1)

您可以再次将"'"添加到字符串中,而不是完美的方式,但适用于当前场景。

def scramble_word(word) -> str:
    index = word.find("'")
    stra = word[0] + ''.join(sorted(word[1:index] + word[index+1:-1], key=str.lower)) + word[-1]
    return stra[:index] + "'" + stra[index:]

答案 1 :(得分:1)

def scramble_word(word) -> str:
    index = word.find("'")
    str = ''.join(sorted(word[0:index] + word[index+1:]))
    return str[:index] + "'" + str[index:]

print(scramble_word("Mo'uSE"))  # -> EM'Sou
print(scramble_word("qu'iz"))  # -> iq'uz

答案 2 :(得分:1)

希望这可能有所帮助:

>>> def scramble_word(word) -> str:
    index = word.find("'")
    sorted_word = ''.join(sorted(word, key=str.lower)).replace("'", "")
    return sorted_word[:index] + "'" + sorted_word[index:]

>>> scramble_word("Mo'uSE")
"EM'Sou"
>>> print(scramble_word("qu'iz"))
iq'uz
>>> 

答案 3 :(得分:1)

<强>代码

def scramble_word(word, keep="'"):
    """Return a scrambled word by sorting middle letters; `keep` character if found."""
    apos_idx = word.find(keep)
    word = word.replace(keep, "")
    shuffled = [word[0]] + sorted(word[1:-1], key=str.lower) + [word[-1]]
    if apos_idx != -1: 
        shuffled.insert(apos_idx, keep)
    return "".join(shuffled)

<强>演示

words = ["Mo'uSE", "qu'iz", "normal"]
for word in words:
    print(scramble_word(word))

# Mo'SuE
# qi'uz
# namorl

保留所有标点符号的更通用的解决方案:

import string


def scramble_word(word):
    """Return a word by sorting middle letters; preserve punctuation."""
    puncts = [(word.find(c), c) for c in word if c in string.punctuation and word.find(c) > 0]
    replaced = [c for c in word if c not in {i[-1] for i in puncts}]
    shuffled = [replaced[0]] + sorted(replaced[1:-1], key=str.lower) + [replaced[-1]]
    [shuffled.insert(pos, p) for pos, p in puncts]
    return "".join(shuffled)

words = ["Mo'uSE", "qu'iz", "normal", "P-u.n*c(t!u;a:tio>n"]
for word in words:
    print(scramble_word(word))

# Mo'SuE
# qi'uz
# namorl
# P-a.c*i(n!o;t:tuu>n

这是通过收集每个单词中的所有(位置,标点符号)对,删除它们,执行加扰算法并最终重新插入标点符号来完成的。