shuffle string in python

PythonString

Python Problem Overview


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

Python Solutions


Solution 1 - Python

>>> import random
>>> s="abcdef123"
>>> ''.join(random.sample(s,len(s)))
'1f2bde3ac'

Solution 2 - Python

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)

Solution 3 - Python

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

Solution 4 - Python

you can use more_itertools.random_permutation

from more_itertools import random_permutation

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

output:

'DFJIEABGCH'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionarielView Question on Stackoverflow
Solution 1 - Pythonghostdog74View Answer on Stackoverflow
Solution 2 - PythonMark ByersView Answer on Stackoverflow
Solution 3 - PythonAnand TripathiView Answer on Stackoverflow
Solution 4 - PythonkederracView Answer on Stackoverflow