How to shuffle a word in Python

In this tutorial, we will learn how to shuffle a word in Python.

Problem

In this problem, we will give a string(word) as input. The compiler will also give a string as output. The output string contains the letters of the word in a randomly shuffled manner.

Example

Let us consider the word “CodeSpeedy”. After shuffling, we will get the result as “pCdodySeee”, “dyCeeSoepd”, “yeCpdedSoe”, etc.
Remember, the results are different because we are randomly shuffling the word. So each time we run the code we shall get a different output.

Algorithm: Shuffle a word in Python

To shuffle the words randomly, we shall use the randint function from the random module.
The steps involved are:

  • Find out the length of the word using the len function and then save it to some variable(say n).
  • Since the string is immutable, we shall store the characters of the string in a character array( say li ). Further operations will be done in that array.
  • for ( i = 0 to n-2)
    store the value of randint(i+1, n-1) at position variable(pos)
    exchange li[i] and li[pos]
  • store the characters of the shuffled list in a string and return the string

The shuffle function

def shuffle(s):
    n = len(s) #n stores the length of the string 
    li = list(s) #since string is immutable, 
                 #we make a list of the characters of the string 

    for i in range(0,n-1): #i is iterated from 0 to n-2
        pos = randint(i+1,n-1) #this function randint will produce a 
                               #random number ranging between i+1 and n-1
        li[pos],li[i] = li[i],li[pos] #exchanging li[pos] and li[i]
    
    res = "" 
    for i in range(n):
        res = res + li[i] #sequentially add the charters of the list 
                          #to the string
    return res

 

Full Python Code

from random import randint

def shuffle(s):
    n = len(s) #n stores the length of the string
    li = list(s)#since string is immutable,
                #we make a list of the characters of the string
    for i in range(0,n-1):  #i is iterated from 0 to n-2
        pos = randint(i+1,n-1) #this function randint will produce a
                               #random number ranging between i+1 and n-1
        li[pos],li[i] = li[i],li[pos]   #exchanging li[pos] and li[i]
    res = ""
    for i in range(n):
        res = res + li[i]    #sequentially add the charters of the list
                             #to the string
    return res

print("Enter a word: ")
s = str(input()) # taking a string input
print(shuffle(s)) #calling the shuffle function

Input

Enter a word: 
CodeSpeedy

Output

oeCdpyedSe

One response to “How to shuffle a word in Python”

  1. Satyam Singh says:

    There is a three-line version to this problem:

    import random as r
    a=input(“Enter a word”)
    print(“”.join(r.sample(a,len(a))))

Leave a Reply

Your email address will not be published. Required fields are marked *