gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:04 25 4
gpt4 key购买 nike

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

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。如何将撇号插入回字符串?

最佳答案

代码

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

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

关于python - 如何对字符串中的字符进行排序但只保留撇号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46531013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com