user8341034
user8341034

Reputation:

Splitting on multiple characters?

Before you say this is a duplicate of Split Strings with Multiple Delimiters?, I think that the solution for this problem should be less complicated than 'importing re' or importing anything because this problem is from a website called Grok Learning where I haven't learnt how to do that yet.

Anyways, my code works fine except for one part. When I enter a word with a full stop after it, for example: "I like Velcro and Kleenex.' The Velcro part turns into the correct key from the dictionary, but Kleenex doesn't because it has . after it meaning the program is searching for 'Kleenex.' instead of 'Kleenex'

I've already split the input by ' ' (a space) but I was wondering how I could split it from multiple things like a '.' as well?

BRANDS = {
  'Velcro': 'hook and loop fastener',
  'Kleenex': 'tissues',
  'Hoover': 'vacuum',
  'Bandaid': 'sticking plaster',
  'Thermos': 'vacuum flask',
  'Dumpster': 'garbage bin',
  'Rollerblade': 'inline skate',
  'Aspirin': 'acetylsalicylic acid'
}

sentence = input('Sentence: ')
words = sentence.split(' ')
for i in words:
  if i in BRANDS:
    sentence = sentence.replace(i, BRANDS[i])
    print(sentence)

Upvotes: 1

Views: 71

Answers (1)

Jebby
Jebby

Reputation: 1955

You could iterate over each item in BRANDS and replace the key with the value in the sentence.

BRANDS = {
  'Velcro': 'hook and loop fastener',
  'Kleenex': 'tissues',
  'Hoover': 'vacuum',
  'Bandaid': 'sticking plaster',
  'Thermos': 'vacuum flask',
  'Dumpster': 'garbage bin',
  'Rollerblade': 'inline skate',
  'Aspirin': 'acetylsalicylic acid'
}

sentence = input("Sentence: ")
for brand in BRANDS:
    sentence = sentence.replace(brand, BRANDS[brand])
print(sentence)

Upvotes: 1

Related Questions