Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swap letters in a string in python

Tags:

python

I am trying to switch the first character in a string and move it to the end of the string. It needs to repeat the rotation a number of n times. For example, rotateLeft(hello,2)=llohe.

I tried doing

def rotateLeft(str,n):
    rotated=""
    rotated=str[n:]+str[:n]
    return rotated 

Is this right, and how would you do it if it remove the last character and move it to the front of the string?

like image 899
Neal Wang Avatar asked Dec 10 '11 17:12

Neal Wang


People also ask

How do I swap characters in a string?

As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.

How do you swap a and b in Python?

The simplest way to swap the values of two variables is using a temp variable. The temp variables is used to store the value of the fist variable ( temp = a ). This allows you to swap the value of the two variables ( a = b ) and then assign the value of temp to the second variable.

How do you reverse two characters in a string Python?

The reversed() Built-in Functionjoin() to create reversed strings. However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.


1 Answers

You can shorten it to

def rotate(strg,n):
    return strg[n:] + strg[:n]

and simply use negative indices to rotate "to the right":

>>> rotate("hello", 2)
'llohe'
>>> rotate("hello", -1)
'ohell'
>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 4)
'ohell'
>>> rotate("hello", -3)
'llohe'
>>> rotate("hello", 6)  # same with -6: no change if n > len(strg)
'hello' 

If you want to keep rotating even after exceeding the length of the string, use

def rotate(strg,n):
    n = n % len(strg)
    return strg[n:] + strg[:n]

so you get

>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 6)
'elloh'
like image 138
Tim Pietzcker Avatar answered Nov 14 '22 20:11

Tim Pietzcker