Python 單詞字母順序不變且全部倒排
設計一個函數,任何語言都可以,實現以下功能:
一個句子,將句子中的單詞全部倒排過來,但單詞的字母順序不變。eg. this is a real world輸出結果為:world real a is this
筆者用Python實現如下:
#! /usr/bin/env python- -coding:utf-8--
def str_reverse(str):
str_dst =str.split()[A1] str_dst.reverse()[A2] return str_dst
if name == ‘main’:
for str_out in str_reverse(raw_input(‘plz input ur sentence:’)): print str_out,</pre>
Python is Python!
[A1]以空格為分隔符,將單詞取出放入list中。
關于split():
string.split(s[, sep[, maxsplit]])
Return a list of the words of thestring s. If the optional second argument sep is absent or None, the words areseparated by arbitrary strings of whitespace characters (space, tab, newline,return, formfeed). If the second argument sep is present and not None, itspecifies a string to be used as the word separator. The returned list willthen have one more item than the number of non-overlapping occurrences of theseparator in the string. If maxsplit is given, at most maxsplit number ofsplits occur, and the remainder of the string is returned as the final elementof the list (thus, the list will have at most maxsplit+1 elements). If maxsplitis not specified or -1, then there is no limit on the number of splits (allpossible splits are made).
The behavior of split on an emptystring depends on the value of sep. If sep is not specified, or specified asNone, the result will be an empty list. If sep is specified as any string, theresult will be a list containing one element which is an empty string
[A2]反轉list
關于reverse():
s.reverse() reverses the items of s inplace
The reverse() methods modify the listin place for economy of space when reversing a large list. To remind you thatthey operate by side effect, they don’t return the reversed list.