If you are working with text data in Python, you might need to shuffle words in the text randomly.
The good news is that Python has a built-in function called random that allows us to shuffle a list of items, including words in a string. In this tutorial, you will learn how to shuffle words in Python.
Steps:
1. Create a string variable with the words you want to shuffle.
1 |
text = "The quick brown fox jumps over the lazy dog" |
2. Split the string into a list of words using the split method.
1 |
words = text.split() |
3. Import the random module to access the shuffle function.
1 |
import random |
4. Shuffle the list of words using the shuffle function.
1 |
random.shuffle(words) |
5. Join the shuffled words into a new string using the join method.
1 |
shuffled_text = " ".join(words) |
6. Print the shuffled text to the console.
1 |
print(shuffled_text) |
Output:
fox The dog quick over jumps lazy the brown The
Conclusion:
Shuffling words in Python is easy with the random module’s shuffle function. By splitting a string of words into a list, shuffling the list, and then joining the shuffled list back into a string, you can quickly shuffle words in any text data. Keep exploring Python’s built-in functions to improve your text analysis and data processing tasks.
Full Code:
1 2 3 4 5 6 7 |
import random text = "The quick brown fox jumps over the lazy dog" words = text.split() random.shuffle(words) shuffled_text = " ".join(words) print(shuffled_text) |