Mike5732
Mike5732

Reputation: 1

Python with dictionary

So i want to have a text like: pretty = [beautiful, attractive, good-looking]

And in python i have an input from the user.

UserInput= input()

I want to check if the UserInput matches any word inside the list. If there is a match i want to replace the word that matched with "Pretty".

I tried this.


userInput = input()
userInput.split()
for word in userInput:
   if word in pretty:
      userInput.replace(word,"pretty")

This does not do anything. It does not replace the matching word.

One more question if i have multiple lists and want to check through all of them. What would be the best way?

Upvotes: 0

Views: 67

Answers (3)

Abhishek Rai
Abhishek Rai

Reputation: 2237

Simple with enumerate

pretty = ['beautiful', 'attractive', 'good-looking']

userInput = input("Enter the word :")
for i, word in enumerate(pretty):
    if userInput == word:
        pretty[i] = 'pretty'

print(pretty)

Test:

Enter the word :attractive
['beautiful', 'pretty', 'good-looking']

Upvotes: 0

Sandsten
Sandsten

Reputation: 757

You have to store userInput.split() to a variable. .split() returns a list but won't directly update userInput. As it is now your, loop will go through each character in userInput and not words.

So try this

userInput = userInput.split()

You have to reassign the userInput variable when you find a match. But before you do that you have to convert the list back to a string

userInput = " ".join(userInput).replace(word, "pretty")

This works for me

pretty = ["beautiful", "attractive", "good-looking"]

userInput = input()
userInput = userInput.split()
for word in userInput:
    if word in pretty:
        userInput = " ".join(userInput).replace(word, "pretty")

print(userInput)

Upvotes: 0

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

.split() and .replace() is not an in-place method like .sort() on list because strings are immutable object in python unlike list which are mutable object in python. While looping, you need to split, not before that. Also, you need to reassign userInput to the new string with word being replaced by some other sub-string.

Try this :

userInput = input()
for word in userInput.split():
   if word in pretty:
      userInput = userInput.replace(word,"pretty")

Upvotes: 1

Related Questions