How to Shuffle a String in Python?

Estimated read time 1 min read

To shuffle a string in Python, you can use the random module, which provides a way to generate random numbers and shuffle lists. Here’s an example of how to shuffle a string in Python:

import random

# Define the string to be shuffled
s = 'hello world'

# Convert the string to a list of characters
chars = list(s)

# Shuffle the list of characters

# Convert the shuffled list back to a string
shuffled = ''.join(chars)

# Print the shuffled string

In this example, the string 'hello world' is converted to a list of characters using the list() function, and the random.shuffle() function is used to shuffle the list of characters in a random order. The join() method is then used to join the shuffled list back into a string. Finally, the shuffled string is displayed on the console using the print() function.

When you run this code, you will see the string 'hello world' shuffled in a random order. Note that this technique can be used to shuffle any string in Python, simply by converting it to a list of characters, shuffling the list, and joining it back into a string using the join() method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply