Hướng dẫn rotation string python
View Discussion Improve Article Save Article View Discussion Improve Article Save Article Given a string of size n, write functions to perform following operations on string.
Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeeksforGee" Input : s = "qwertyu" d = 2 Output : Left rotation : "ertyuqw" Right rotation : "yuqwert" Method 1: We have existing solution for this problem please refer Left Rotation and Right Rotation of a String link. We will solve this problem quickly in python using String Slicing. Approach is very simple,
Implementation: Python3
Output: Left Rotation : eksforGeeksGe Right Rotation : ksGeeksforGee Method 2: We use extended string to rotate the string. We will solve this problem quickly in python by slicing extended string. Approach is very simple, Use extended string Extend_str, for Left rotation
Lfirst = Extended_str[n : l1+n] . For Right rotation Rfirst = str[l1-n : l2-n]. Implementation: Python3
Output Left Rotation : ksGeeksforGee Right Rotation : ksGeeksforGee I was trying to make the string
asked Feb 4, 2018 at 10:55
2 Here is one way:
Alternatively,
answered Feb 4, 2018 at 11:06
jppjpp 151k31 gold badges256 silver badges317 bronze badges 1 You can slice and add strings:
This gives you the last character:
and this everything but the last:
Finally, add them with
answered Feb 4, 2018 at 10:58
Mike MüllerMike Müller 79k18 gold badges157 silver badges159 bronze badges 2 Here is what I use to rotate strings in Python3: To rotate left by n:
To rotate right by n:
answered Mar 18, 2020 at 23:50
Clayton C.Clayton C. 8611 gold badge8 silver badges16 bronze badges Here is a simple way of looking at it...
answered Aug 30, 2019 at 14:28
KonchogKonchog 1,79018 silver badges21 bronze badges I would agree with Mike Müller's answer:
I would like to share another way of looking at
This means that it is starting from the start and including everything except for s[-1]. I hope this helped. answered Mar 16, 2019 at 20:59
Not the answer you're looking for? Browse other questions tagged python string or ask your own question. |