题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student.
a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
python split()
Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
语法:
str.split(str="", num=string.count(str)).
str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num – 分割次数。默认为 -1, 即分隔所有。
返回分割后的字符串列表。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
txt = "Google#Runoob#Taobao#Facebook"
# 第二个参数为 1,返回两个参数列表
x = txt.split("#", 1)
print x # ['Google', 'Runoob#Taobao#Facebook']
List reverse()方法
reverse() 函数用于反向列表中元素。
该方法没有返回值,但是会对列表的元素进行反向排序。
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.reverse()
print "List : ", aList # List : ['xyz', 'abc', 'zara', 'xyz', 123]
Python strip()方法
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
str.strip([chars]);
chars – 移除字符串头尾指定的字符序列。
返回移除字符串头尾指定的字符生成的新字符串。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "00000003210Runoob01230000000";
print str.strip( '0' ); # 去除首尾字符 0
#3210Runoob0123
str2 = " Runoob "; # 去除首尾空格
print str2.strip();
# Runoob
答案参考:
来源 牛客网
链接:
https://www.nowcoder.com/ta/coding-interviews/question-ranking?tpId=13&tqId=11197&uuid=3194a4f4cf814f63919d0790578d51f3&rp=1&lang=5&lang=11
# -*- coding:utf-8 -*-
class Solution:
def ReverseSentence(self, s):
# write code here
l = s.split(' ')
return ' '.join(l[::-1])