Python练习第七题,我要倒过来看

浏览: 2307

image.png

更舒适的阅读体验: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())

image.png

二、解法:切片

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

# the easiest way to reverse a string in python is actually the following way:
# in python you can treat the string as an array by adding [] after it and
# the colons inside represent str[start:stop:step] where if step is a negative number
# it'll loop through the string backwards

return str[::-1]

print (FirstReverse(input()))

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

image.png

三、切片详解

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]
'ace'
>>> 'abcde'[::-2]
'eca'
>>> 'abcde'[::-1]
'edcba'

表示从第一个字符开始截取,间隔2个字符取一个。

推荐阅读:官方文档 3. An Informal Introduction to Python

廖雪峰的教程 切片

更多解法:

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

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

推荐 6
本文由 崔斯特呀 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

3 个评论

图片看不到
我可以看见啊~
我也看到啊,全美女,这样看图片也不困,哈哈

要回复文章请先登录注册