Rotating strings in Python

后端 未结 5 715
面向向阳花
面向向阳花 2020-12-03 22:51

I was trying to make the string HELLO to OHELL in Python. But couldn\'t get any way to rotate it without working with loops. How to code for it in

5条回答
  •  天涯浪人
    2020-12-03 23:16

    Here is one way:

    def rotate(strg, n):
        return strg[n:] + strg[:n]
    
    rotate('HELLO', -1)  # 'OHELL'
    

    Alternatively, collections.deque ("double-ended queue") is optimised for queue-related operations. It has a dedicated rotate() method:

    from collections import deque
    
    items = deque('HELLO')
    items.rotate(1)
    
    ''.join(items)  # 'OHELL'
    

提交回复
热议问题