python翻转字符串

「爱情、让人受尽委屈。」 2023-08-17 15:33 210阅读 0赞

Python 列表截取可以接收第三个参数,参数作用是截取的步长,以下实例在索引 1 到索引 4 的位置并设置为步长为 2(间隔一个位置)来截取字符串:

1530206-20190814165832332-1035043610.png

如果第三个参数为负数表示逆向读取。

以下实例用于翻转字符串:

实例1:

  1. def reverseWords(input):
  2.   # 通过空格将字符串分隔符,把各个单词分隔为列表
  3. inputWords = input.split(" ")
  4. print(type(inputWords))
  5. print(inputWords)
  6.   # 翻转字符串
  7. # 假设列表 list = [1,2,3,4],
  8. # list[0]=1, list[1]=2 ,而 -1 表示最后一个元素 list[-1]=4 ( 与 list[3]=4 一样)
  9. # inputWords[-1::-1] 有三个参数
  10. # 第一个参数 -1 表示最后一个元素
  11. # 第二个参数为空,表示移动到列表末尾
  12. # 第三个参数为步长,-1 表示逆向
  13. inputWords = inputWords[-1::-1]
  14. print(inputWords)
  15.   # 重新组合字符串
  16. output = ' '.join(inputWords)
  17. return output
  18. if __name__ == '__main__':
  19. input = 'i like tets'
  20. rw = reverseWords(input)
  21. print(rw)
  22. 结果如下:


[‘i’, ‘like’, ‘tets’]
[‘tets’, ‘like’, ‘i’]
tets like i

Process finished with exit code 0

实例2:将s = “abcdef”反转成 “fedcba”

  1. input1='string'
  2. print(input1[::-1])

转载于:https://www.cnblogs.com/hellomaster/p/11353193.html

发表评论

表情:
评论列表 (有 0 条评论,210人围观)

还没有评论,来说两句吧...

相关阅读

    相关 翻转字符串

    翻转字符串 字符串反转 题目分析 翻转字符串(2) 题目分析 字符串反转 来源:牛客网 链接:https://www.n

    相关 翻转字符串

    题目描述 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的