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

3f4a9ec9fd204955c72f7f64da8ce7cb.png

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

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

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值