2

I'm try to make this: your enter a word like this: Happy and than the program returns somethings like : yppaH or appHy.

The problem is that I get just one letter : y or H, etc..

import random
def myfunction():
    """change letter's position"""
    words = input("writte one word of your choice? : ")
    words = random.choice(words)
    print('E-G says : '+ words)
2
  • Do you want the word to be just reversed? Commented Dec 4, 2016 at 11:33
  • 1
    random.choice() picks one letter. You might reverse the word or do the other transformation you mentioned Happy to appHy, store these in a say list, than use random.choice on that list. Voila. Commented Dec 4, 2016 at 11:34

3 Answers 3

6

You have to use sample, not choice.

import random
# it is better to have imports at the beginning of your file
def myfunction():
    """change letter's position"""
    word = input("writte one word of your choice? : ")
    new_letters = random.sample(word, len(word))
    # random.sample make a random sample (without returns)
    # we use len(word) as length of the sample
    # so effectively obtain shuffled letters
    # new_letters is a list, so we have to use "".join
    print('E-G says : '+ "".join(new_letters))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your explanation! :)
5

Use random.shuffle on a conversion of the string in a list (works in-place)

Then convert back to string using str.join

import random

s =  "Happy"

sl = list(s)
random.shuffle(sl)

print("".join(sl))

outputs:

pyapH
Hpayp

Comments

1

If you want to print reversed word this would be fastest approach:

print(input("writte one word of your choice? : ")[::-1])

1 Comment

but OP doesn't want that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.