Reputation: 75
I'm trying to make a simple encryptions using a random abc to convert it But i'm having a problem with the Random library.
import random
def random(st = 'i love cats')
abc = 'abcdefghijklmnopqrstuvwxyz'
randomabc = abc
random.shuffle(randomabc)
print(randomabc)
the expected output is a random order of the ABC the actual output is an error (the code stops before the print because of the error)
Upvotes: 0
Views: 225
Reputation: 20490
You cannot shuffle a string
, it is an immutable object which cannot be changed once it is assigned.
Instead you need to convert it to a list (A mutable object), shuffle the list via random.shuffle which shuffles the list in-place, and then convert the list back to the string.
import random
abc = 'abcdefghijklmnopqrstuvwxyz'
#Convert string to list
li = list(abc)
#Shuffle the list inplace
random.shuffle(li)
#Convert list to string
print(''.join(li))
The output will be
dpfozwhyxalebnqrmstcjvuigk
qgjefyrahobpnxtzmsdkwivlcu
nchkriewsuxdzyjfgvpblomtqa
.....
In addition to it, another alternative (a one-liner) is to use random.sample to pick len(abc)
unique samples, and join all of them in a string (Thanks @JonClements) but it's more suited for a one off reshuffle
print(''.join(random.sample(abc, len(abc))))
Upvotes: 1
Reputation: 24038
Since abc
is a string, which are immutable (you cannot change it in-place) you cannot do it like that.
Instead you have to:
split the string into a list of characters.
shuffle that list
join the character list back into a string
import random
abc = 'abcdefghijklmnopqrstuvwxyz'
ls = list(abc)
random.shuffle(ls)
abc = ''.join(ls)
print(abc)
Example output:
erbkvownuhcmfljtgqpyiazdxs
Also: Never name your functions or .py files with names clashing with the standard library. In this case your function is the same name as the random
module, and that is a huge problem.
Upvotes: 2
Reputation: 7812
As I mentioned in comments, you should give your functions names different from python keywords, imported modules, class names, etc. Try to rename your method form random
to random_alphabet
.
import random
def random_alphabet(st = 'i love cats'):
pass
Upvotes: 1