標籤:

Python練習第七題,我要倒過來看

更舒適的閱讀體驗:Python聯繫第七題,我要倒過來看

一、Challenge

Using the Python language, have the function FirstReverse(str) take the str parameter being passed and return the string in reversed(顛倒的) order. For example: if the input string is "Hello World and Coders" then your program should return the string sredoC dna dlroW olleH.

題目意思是,給定字元串,返回原來的倒序。例如給出的是「Hello World and Coders」,返回「sredoC dna dlroW olleH.」

Sample Test Cases

Input:"coderbyte"

Output:"etybredoc"

Input:"I Love Code"

Output:"edoC evoL I"

Hint

Think of how you can loop through a string or array of characters backwards to produce a new string.

def FirstReverse(str): nn # code goes here n return strnn# keep this function call here nprint FirstReverse(raw_input())n

二、解法:切片

A simple way to reverse a string would be to create a new string and fill it with the characters from the original string, but backwards. To do this, we need to loop through the original string starting from the end, and every iteration of the loop we move to the previous character in the string. Here is an example:

def FirstReverse(str): nn # the easiest way to reverse a string in python is actually the following way:n # in python you can treat the string as an array by adding [] after it and n # the colons inside represent str[start:stop:step] where if step is a negative numbern # itll loop through the string backwards nn return str[::-1]n nprint (FirstReverse(input())) n

非常簡潔 str[::-1] 就可以完成目標。

三、切片詳解

1、取字元串中第幾個字元

>>> hello[0]#表示輸出字元串中第一個字元nhn>>> hello[-1]#表示輸出字元串中最後一個字元non

2、字元串分割

>>> hello[1:3]neln

#第一個參數表示原來字元串中的下表

#第二個參數表示分割後剩下的字元串的第一個字元 在 原來字元串中的下標

注意,Python從0開始計數

3、幾種特殊情況

>>> hello[:3]#從第一個字元開始截取,直到最後nheln>>> hello[0:]#從第一個字元開始截取,截取到最後nhellon>>> hello[:]nhellon

4、步長截取

>>> abcde[::2]nacen>>> abcde[::-2]necan>>> abcde[::-1]nedcban

表示從第一個字元開始截取,間隔2個字元取一個。

推薦閱讀:官方文檔 3. An Informal Introduction to Python

廖雪峰的教程 切片

更多解法:

def FirstReverse(str): nn # reversed(str) turns the string into an iterator object (similar to an array)n # and reverses the order of the charactersn # then we join it with an empty string producing a final string for usnn return .join(reversed(str))n nprint(FirstReverse(input()))n

使用了什麼語法?評論中見。

======================================================================3.8更新

1、Python List reverse()方法

reverse() 函數用於反向列表中元素。

>>> a = [1,2,3,4,5]n>>> a.reverse()n>>> an[5, 4, 3, 2, 1]n

2、Python中的join()函數的用法

語法: sep.join(seq)

參數說明

sep:分隔符。可以為空

seq:要連接的元素序列、字元串、元組、字典

上面的語法即:以sep作為分隔符,將seq所有的元素合併成一個新的字元串

返回值:返回一個以分隔符sep連接各個元素後生成的字元串

>>> s="abcd"n>>> ",".join(s)na,b,c,dn>>> "|".join([a,b,c])na|b|cn>>> ",".join((a,b,c))na,b,cn>>> ",".join({a:1,b:2,c:3})na,c,bn#要保證a,b等的整體性,就必須用元組n#如果不用元組,會按每個字元分開,a,b內部也會被分開:n>>> k1="ttt"n>>> k2="sss"n>>> a=k1+k2n>>> ",".join(a)nt,t,t,s,s,sn

推薦閱讀:

TAG:Python |