1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python把一个英语句子倒过来_Python练习第七题 我要倒过来看

python把一个英语句子倒过来_Python练习第七题 我要倒过来看

时间:2024-03-21 16:29:20

相关推荐

python把一个英语句子倒过来_Python练习第七题 我要倒过来看

一、Challenge

Using the Python language, have the function FirstReverse(str) take thestrparameter 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 stringsredoC 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())

二、解法:切片

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]就可以完成目标。

三、切片详解

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个字符取一个。

更多解法: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()))

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。