简体   繁体   English

用前一个单词的字母反向替换每个单词的第一个字母

[英]Reverse-replacing the first letter of each word with the letter of the previous word

I've written a function that takes a message (string) as an input and replaces the first letter of each word with the first letter of the previous word (for the very first word, I take the first letter of the last word):我编写了一个函数,它将消息(字符串)作为输入,并将每个单词的第一个字母替换为前一个单词的第一个字母(对于第一个单词,我取最后一个单词的第一个字母):

def changeFirst(message):
    msg_list=list(message)
    j=0
    pre=msg_list[j]
    for i in range(len(msg_list)):
        if msg_list[i]==' ':
            nextpre=msg_list[i+1]
            msg_list[i+1]=pre
            pre=nextpre
    msg_list[0]=pre
    msg_list=''.join(msg_list)
    return msg_list

changeFirst("now you are in love with me")
mow nou yre an iove lith we

I want to write a funtion UnchangeFirst() which reverses this function, for example it should work like this:我想写一个函数UnchangeFirst()来反转这个函数,例如它应该像这样工作:

UnchangeFirst("mow nou yre an iove lith we")
now you are in love with me

How can I reverse this function?我怎样才能反转这个功能?

Here it is!这里是!

def changedAgain(message2):
    msg_list = list(message2)
    j = 0
    first=msg_list[0]
    for i in range(len(msg_list)):
        if msg_list[i]==' ':
            msg_list[j]=msg_list[i+1]
            msg_list[i+1]=msg_list[j]
            j=i+1

    msg_list[j]=first
    return(''.join(msg_list))

message2="mow nou yre an iove lith we"

print(changedAgain(message2))
>>> "now you are in love with me"

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

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