如何查找字符串的开头和结尾

时间:2016-04-16 21:12:14

标签: python string if-statement

意图是编写一个可以反转字符串中单词的函数。因此,如果输入是:“我是学生”,则输出应该是“我是学生”

我在Python中有以下代码,它首先反转字符串中的所有字符,然后循环反转的句子以反转单词并将它们打印到“最终句子”变量。

因为我要检查的条件只是一个空格,所以第一个单词不会被打印,即如果输入是“我是学生”我的代码可以工作(注意“我”之前的空格)...但是如果输入是“我是学生”,那么输出就是“学生上午”

我需要知道如何修改我的IF语句,以便它不会错过第一个单词

def reverse(sentence):
    count = 0
    new_sentence = ''
    final_sentence = ''
    counter = 0
    word = ''

    for char in sentence[::-1]:
        new_sentence = new_sentence + char


    for char in new_sentence:
        if char != " ":
            count = count + 1
            continue
        else:
            for i in new_sentence[count-1::-1]:

                if i != " ":    
                    word = word + i
                else:
                    break

        count = count + 1
        final_sentence = final_sentence + " " + word
        word = ''
    print final_sentence

reverse("I am a student")

2 个答案:

答案 0 :(得分:2)

我不确定你为什么要做这么复杂的循环?您可以将句子拆分,反转,然后再次加入:

>>> ' '.join('I am a student'.split(' ')[::-1])
'student a am I'

将其转换为函数:

def reverse_sentence(sentence):
    return ' '.join(sentence.split(' ')[::-1])

答案 1 :(得分:2)

你在代码中做了几件奇怪的事情。例如:

new_sentence = ''
for char in sentence[::-1]:
    new_sentence = new_sentence + char

您通过连接构建的字符串已存在于sentence[::-1]中。你刚刚完成new_sentence = sentence[::-1]

您可以使用enumerate()检查第一个单词,并检查句子中该点之前是否有空格:

for idx,char in enumerate(new_sentence):
    if char != " " or ' ' not in new_sentence[:idx]:

然而,实现实际目标的最简单方法是使用split(),自动将空格分割为空格。一旦你扭转了它,就用join()将它重新组合在一起。

def reverse(sentence):
    return ' '.join(sentence.split()[::-1])