重新排列字符,使所有辅音出现在元音之前

2024-04-24 15:40:36 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个python函数,以便

奇数词位置:反转在

偶数词位置:重新排列使所有辅音 出现在元音之前,其顺序不应改变

在输入:太阳在东方崛起 输出:eht snusesir ni eht stea公司

我已将字符串反转,但无法重新排列字符。 我们可以使用append和join函数还是需要在末尾进行交换。 基本上,弦的旋转已经完成了,我们怎样才能达到这个目的。在

def encrypt_sentence(sentence):
    vowel_set = set("aeiouAEIOU")
    final_list=[]
    word=sentence.split()
    for i in range(0,len(word)):
        if((i%2)==0):
            final_list.append(word[i][::-1])
        else:
           final_list.append("".join(c for c in word if c not in vowel_set))
 print(final_list)                   
encrypt_sentence("the sun rises in the east")   

Tags: the函数inforifsentencelistword
3条回答
def encrypt_sentence(sentence):
    vowel=set("AEIOUaeiou")
    s1=sentence
    var=""

    li = list(sentence.split(" "))
    for i in range(len(li)):
        var=li[i]
        if(i%2==0):
            var=var[::-1]
            li[i]=var

        else:
            t=""
            t2=""
            for j in var:
                if(j in vowel):
                    t2=t2+j
                else:
                    t=t+j
            t=t+t2
            li[i]=t
    var2=""
    for i in range(len(li)):
        var2=var2+li[i]
        if(i != len(li)-1):
            var2=var2+" "
    return var2


sentence="The sun rises in the east"
encrypted_sentence=encrypt_sentence(sentence)
print(encrypted_sentence)

我会反复检查字母以跟踪元音和辅音,然后在末尾使用join。在

def encrypt_sentence(sentence):
    vowel_set = set("aeiouAEIOU")
    final_list=[]
    word=sentence.split()
    for i in range(0,len(word)):
        if((i%2)==0):
            final_list.append(word[i][::-1])
        else:  # do rearrangement
            vowels = list()
            consonants = list()
            for letter in word[i]:
                if letter in vowel_set:
                    vowels.append(letter)
                else:
                    consonants.append(letter)
            new_string = "".join(consonants) + "".join(vowels)
            final_list.append(new_string)
    return final_list

尝试使用两种列表理解法:

word='testing'
vov=[x if x in vowel_set else '' for x in word]
cons=[x if x not in vowel_set else '' for x in word]
('').join(cons+vov)

相关问题 更多 >