Fork me on GitHub

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): 

   # code goes here 
   return str

# keep this function call here  
print FirstReverse(raw_input())

二、解法:切片

环境:Python3.5

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): 

    return str[::-1]

print (FirstReverse(input()))  

非常简洁str[::-1]就可以完成目标。

三、切片详解

1、取字符串中第几个字符

>>> 'hello'[0]#表示输出字符串中第一个字符
'h'
>>> 'hello'[-1]#表示输出字符串中最后一个字符
'o'

2、字符串分割

>>> 'hello'[1:3]
'el'

第一个参数表示原来字符串中的下表
第二个参数表示分割后剩下的字符串的第一个字符 在 原来字符串中的下标

注意,Python从0开始计数

3、几种特殊情况

>>> 'hello'[:3]#从第一个字符开始截取,直到最后
'hel'
>>> 'hello'[0:]#从第一个字符开始截取,截取到最后
'hello'
>>> 'hello'[:]
'hello'

4、步长截取

>>> 'abcde'[::2]#表示从第一个字符开始截取,间隔2个字符取一个。
'ace'
>>> 'abcde'[::-2]
'eca'
>>> 'abcde'[::-1]
'edcba'

推荐阅读:

官方文档
https://docs.python.org/3/tutorial/introduction.html#strings

廖雪峰的教程

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431756919644a792ee4ead724ef7afab3f7f771b04f5000

更多解法:

def FirstReverse(str): 

  # reversed(str) turns the string into an iterator object (similar to an array)
 # and reverses the order of the characters
 # then we join it with an empty string producing a final string for us

     return ''.join(reversed(str))

print(FirstReverse(input()))

使用了什么语法?评论中见。