美文网首页
Python将字符串进行反转

Python将字符串进行反转

作者: 盖码范 | 来源:发表于2019-07-11 12:08 被阅读0次

    将字符串"ilovechina"进行反转

    先来个错误的例子!!!

    "ilovechina".reverse() #直接将字符串用reverse异常,reverse适用于list(列表)
    
    Traceback (most recent call last):
      File "/home/lfg/virtua/spider/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3296, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-29-38da92838417>", line 1, in <module>
        "ilovechina".reverse()
    AttributeError: 'str' object has no attribute 'reverse'
    

    上面错误的示范,reverse适用于list(列表),不能将字符串反转。

    方法一:

    使用切片的方法:"ilovechina"[::-1]

    "ilovechina"[::-1] 
    
    Out[17]: 'anihcevoli'
    

    方法二

    使用reversed()方法: ''.join(reversed('ilovechina'))

    ''.join(reversed('ilovechina'))
    
    Out[28]: 'anihcevoli'
    

    总结

    reverse() :函数用于反向列表中元素。
    reversed():函数是返回序列seq的反向访问的迭代子。参数可以是列表,元组,字符串

    相关文章

      网友评论

          本文标题:Python将字符串进行反转

          本文链接:https://www.haomeiwen.com/subject/mvmrkctx.html