100

I am looking for a function or short program that receives a string (up to 10 letters) and shuffles it.

5 Answers 5

159
>>> import random
>>> s="abcdef123"
>>> ''.join(random.sample(s,len(s)))
'1f2bde3ac'
Sign up to request clarification or add additional context in comments.

Comments

117

There is a function shuffle in the random module. Note that it shuffles in-place so you first have to convert your string to a list of characters, shuffle it, then join the result again.

import random
l = list(s)
random.shuffle(l)
result = ''.join(l)

1 Comment

+1 for the "in-place". Thus print random.shuffle(['a', 'b', 'c']) will return None. We have to use L = ['a', 'b', 'c'] then random.shuffle(L) and print L instead.
9

Python Provides the various solutions to shuffle the string:

1. External library: python-string-utils

  • first install the python-string-utils library
    • pip install python_string_utils
  • use string_utils.shuffle() function to shuffle string
  • please use the below snippet for it

Code Snippet

import string_utils
print string_utils.shuffle("random_string")

Output:

drorntmi_asng

2. Builtins Method: random.shuffle

Please find the code below to shuffle the string. The code will take the string and convert that string to list. Then shuffle the string contents and will print the string.

import random
str_var = list("shuffle_this_string")
random.shuffle(str_var)
print ''.join(str_var)

Output:

t_suesnhgslfhitrfi_

3. External Library: Numpy

import numpy
str_var = list("shuffle_this_string")
numpy.random.shuffle(str_var)
print ''.join(str_var)

Output:

nfehirgsu_slftt_his

Comments

1

you can use more_itertools.random_permutation

from more_itertools import random_permutation

s = 'ABCDEFGHIJ'
''.join(random_permutation(s))

output:

'DFJIEABGCH'

Comments

0

Here is a helper that uses random to non-destructively shuffle, string, list or tuple:

def shuffle_any(o):
    is_l=is_t=False
    if isinstance(o, str):
        l = list(o)
    elif isinstance(o, list):
        l = o[:]
        is_l = True
    elif isinstance(o, tuple):
        is_t = True
        l = list(o)
    else:
        raise Exception("o is None!" if o is None \
                else f"Unexpected type: {o.__class__.__name__}")
    random.shuffle(l)
    return l if is_l else tuple(l) if is_t else ''.join(l)

Usage:

print(f"shuffle_any('abcdefg'): {shuffle_any('abcdefg')}")
print(f"shuffle_any([1,2,3,4,5]): {shuffle_any([1,2,3,4,5])}")
print(f"shuffle_any((1,2,3,4,5)): {shuffle_any((1,2,3,4,5))}")

Output:

shuffle_any('abcdefg'): dfceabg
shuffle_any([1,2,3,4,5]): [5, 2, 3, 4, 1]
shuffle_any((1,2,3,4,5)): (4, 3, 2, 5, 1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.