Rotating strings in Python

后端 未结 5 696
面向向阳花
面向向阳花 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:04

    Here is a simple way of looking at it...

    s = 'HELLO'
    for r in range(5):
        print(s[r:] + s[:r])
    
    
    HELLO
    ELLOH
    LLOHE
    LOHEL
    OHELL
    
    0 讨论(0)
  • 2020-12-03 23:12

    Here is what I use to rotate strings in Python3:

    To rotate left by n:

    def leftShift(text,n):
        return text[n:] + text[:n]
    

    To rotate right by n:

    def rightShift(text,n):
        return text[-n:] + text[:-n]
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-03 23:20

    You can slice and add strings:

    >>> s = 'HELLO'
    >>> s[-1] + s[:-1]
    'OHELL'
    

    This gives you the last character:

    >>> s[-1]
    'O'
    

    and this everything but the last:

    >>> s[:-1]
    'HELL'
    

    Finally, add them with +.

    0 讨论(0)
  • 2020-12-03 23:24

    I would agree with Mike Müller's answer:

    s = 'HELLO'
    s = s[-1] + s[:-1]
    

    I would like to share another way of looking at s[:-1]

    s[0:-1]
    

    This means that it is starting from the start and including everything except for s[-1]. I hope this helped.

    0 讨论(0)
提交回复
热议问题