tags:

views:

234

answers:

3

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

+6  A: 

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)
Mark Byers
@Mark: no (was that wrong?)
N 1.1
>>> s=string >>>random.shuffle(s)returnn an error
ariel
@ariel: s="string"
N 1.1
+4  A: 
>>> import random
>>> s="abcdef123"
>>> ''.join(random.sample(s,len(s)))
'1f2bde3ac'
ghostdog74
+1 interesting variation for a one-liner.
Mark Byers
Hey, that's my password!
extraneon
that don't give the good result if there is repetition in the string for example s="abcdef123a"
Xavier Combelle
@Xavier Combelle: It works fine with repetition. Have you tried it?
Daniel Stutzbach
+1 nice, even though slower than Mark's answer
ΤΖΩΤΖΙΟΥ
@Daniel Stutzbach My mistake I surely misread the documentation
Xavier Combelle
A: 

An alternate take for shuffling a string:

# Python < 3
import random, array

def shuffle_text(text):
    if isinstance(text, unicode):
        temp= array.array('u', text)
        converter= temp.tounicode
    else:
        temp= array.array('c', text)
        converter= temp.tostring
    random.shuffle(temp)
    return converter()

I added this answer just for completeness' sake; on my slow home server, it is faster for small input strings (but the difference is very small), while it is slower for larger strings.

ΤΖΩΤΖΙΟΥ