Python ?
If im wanting to print a word that is input by the user in random order. For example the word "hello" printed like "llohe". How could I does this?
You can split the string then use the shuffle method from the random module, then join the list back into a string.
You probably wouldn't actually print the word in random order, rather you'd scramble the word and then print it. To scramble the word would be to run the string through a loop that would randomly choose 2 characters from that string and swap them. Do this a few times, then print out the scrambled word.
If you're looking for Python code, I can't help you there, but that would be the process for something like this.
If you're looking for Python code, I can't help you there, but that would be the process for something like this.
The random.shuffle method will shuffle the elements of a sequence in random manner, but it requires that the sequence support item assignment, which means you can't pass a string to it. Fortunately, converting a string to a list is trivial, as is converting a list to a string:
import randomrandom.seed()def shuffle(word): word = list(word) random.shuffle(word) return ''.join(word)if __name__ == '__main__': word = raw_input("Please enter a single word:") print "Your word, shuffled, is", shuffle(word)
Note that the forum appears to have mangled one of Oluseyi's lines: the one with the call to join should have 2 adjacent single quotes, not just 1.
it means the code will only execute when the program is called as a script, like
and not when it is imported, this a good way to test modules
python script.py
and not when it is imported, this a good way to test modules
In a nutshell, python files are usually executed in two ways: when run from the command line like python myscript.py or when imported. The if __name__ == '__main__': causes the following code to be executed only if the script isn't being imported.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement