首页 > 解决方案 > 如何在不使用 if 条件作为索引的情况下获取给定字符串中的最后一个单词?

问题描述

Q.编写一个python函数,encrypt_sentence(msg),它接受一条消息并根据下面给出的规则对其进行加密并返回加密的消息。

奇数位置的单词 -> 反转它

偶数位置的单词 -> 重新排列字符,使所有辅音出现在元音之前,并且它们的顺序不应改变

注意:假设句子以单词开头,单词之间只有一个空格。

在必要时执行区分大小写的字符串操作。

#Rearranging the characters so that all consonants appear before the vowels and their order should not change

def consonants_vowels(str):


    vowels_string = "aAeEiIoOuU"  # all Vowels in lowercase and uppercase
    vowel = ""
    consonants = ""

    for i in range(0, len(str)):
        if str[i] in vowels_string:
            vowel = vowel + str[i]          #adding vowels
        else:
            consonants += str[i]            #adding consonants

    return consonants + vowel + " "  # " " to make space between words


str = "How to resolve"

count = 1

word = ""

final_string = ""

for i in range(0, len(str)):

    if str[i] != " " and i + 1 != len(str): #getting each word from string

        word += str[i]

    else:

        if count % 2 != 0:    #to check word at odd postion

            final_string += word[::-1] + " "    #reversing string at odd position

        else:

            final_string = final_string + consonants_vowels(word)

        count += 1
        word = ""

print(final_string)

预期输出:woH to evloser

代码输出:woH to vloser

标签: pythonstringstring-formatting

解决方案


这花了我一分钟,但你的问题的答案是一步一步调试的问题(一步一步地通过你的程序,直到发生一些你不会预料到的事情/发生了一些事情)。

在这种情况下,问题在于您的最后一个字母循环。那是当您检查i + 1 !- len(str)您的问题是否是您仅将字母添加str[i]wordIFFi != len(str)但当然i+1 == len(str)是在循环的最后执行时,因此它不会将字母添加e到单词中,因此,正如我们所料,当它反转这个词(它正确地)也没有e

肯定有几种方法可以解决这个问题,但我会这样做:

首先,我们确实希望在i = len(str)- 在您的示例文本中 i = 13 时添加字母,因此我们将从该行中删除 +1。

接下来,我们需要再次运行循环之后 i = 13 循环(添加 的那个e),以便我们可以检查我们是否完成(也就是说,if i >= len(str)或者换句话说,我们检查它是否不是 - <- - 然后放到else中,因为--14 < 14现在是假的。所以我们+1将从之前的那个开始,并将其粘贴在循环将要执行的次数中--for i in range(0, len(str)+1):所以这将是当i = 14(这是out ) 的索引,str所以...

我们还需要交换条件中的条件,and因为str[i]i = 14长度为 14 的字符串中没有第 15 项(索引为 14)时会抛出错误。

这是最终的工作代码。希望解释能帮助您了解将来如何执行此操作。

#Rearranging the characters so that all consonants appear before the vowels and their order should not change
def consonants_vowels(str):
    vowels_string = "aAeEiIoOuU"  # all Vowels in lowercase and uppercase
    vowel = ""
    consonants = ""
    for i in range(0, len(str)):
        if str[i] in vowels_string:
            vowel = vowel + str[i]          #adding vowels
        else:
            consonants += str[i]            #adding consonants
    return consonants + vowel + " "  # " " to make space between words

str = "How to resolve"
count = 1
word = ""
final_string = ""

for i in range(0, len(str)+1):
    if i < len(str) and str[i] != " " : #getting each word from string
        word += str[i]
    else:
        if count % 2 != 0:    #to check word at odd postion
            final_string += word[::-1] + " "    #reversing string at odd position
        else:
            final_string = final_string + consonants_vowels(word)
        count += 1
        word = ""
        
print(final_string)

在此处输入图像描述


推荐阅读