【问题标题】:Reverse-replacing the first letter of each word with the letter of the previous word用前一个单词的字母反向替换每个单词的第一个字母
【发布时间】:2020-11-17 20:40:50
【问题描述】:

我写了一个函数,它将消息(字符串)作为输入,并将每个单词的首字母替换为前一个单词的首字母(对于第一个单词,我取最后一个单词的首字母)词):

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

我想写一个函数UnchangeFirst()来反转这个函数,例如它应该像这样工作:

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

如何反转这个函数?

【问题讨论】:

  • 好吧,你有没有尝试为它写代码?你遇到了什么具体的困难?你能解释一下你将如何手工解决这个问题吗?你不能将这个过程的哪一部分翻译成代码?

标签: python for-loop if-statement reverse


【解决方案1】:

来了!

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    相关资源
    最近更新 更多