shuffle a string in python

We can shuffle a string in Python using the random module. Here is an example code snippet to shuffle a string in Python:

main.py
import random

original_string = "hello, world!"
string_list = list(original_string)  # Convert the string to a list of characters
random.shuffle(string_list)  # Shuffle the list
shuffled_string = "".join(string_list)  # Convert the list back to a string
print(shuffled_string)
278 chars
8 lines

This code will output a shuffled version of the original string. The list() function is used to convert the string to a list of individual characters, which can be shuffled using the shuffle() function from the random module. Finally, we convert the shuffled list back into a string using the join() function with an empty separator string ("").

related categories

gistlibby LogSnag