2

I have a task that was assigned to me for homework. Basically the problem is:

Write a program that can get rid of the brand names and replace them with the generic names.

The table below shows some brand names that have generic names. The mapping has also been provided to you in your program as the BRANDS dictionary.

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

This is my code:

sentence = input('Sentence: ')

sentencelist = sentence.split()
for c in sentencelist:
  if c in BRANDS:
    d = c.replace(c, BRANDS[c])
    print(d, end=' ')
  else:
    print(c, end=' ')

My output:

Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.  

Expected output:

Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.

It looks the same, but in my output there was an extra whitespace after 'shoes.' when there isn't supposed to be a whitespace. So how do I remove this whitespace?

I know you could do rstrip() or replace() and I tried it, but it would just jumble everything together when I just need to remove the trailing whitespace and not remove any other whitespace. If the user put the brand name in the middle of the sentence, and I used rstrip(), it would join the brand name and the rest of the sentence together.

3
  • Did you try 'sentence = sentence.rstrip()' before the line 'sentencelist = sentence.split()' ?
    – kkblue
    Aug 21, 2018 at 5:22
  • 1
    print(d, end=' ') is adding a space to the end of the last line you print in the sentence aswell Aug 21, 2018 at 5:24
  • @kkblue: That's pointless; str.split() with no argument (or explicit split argument of None) already implicitly strips leading and trailing whitespace along with splitting on runs of whitespace. Aug 21, 2018 at 5:33

4 Answers 4

2

The key is to use a string's join method to concatenate everything for you. For example, to put a space between a bunch of strings without putting a space after the last bit, do

' '.join(bunch_of_strings)

The strings have to be in an iterable, like a list, for that to work. You could make the list like this:

edited_list = []
for word in sentence_list:
    if word in BRANDS:
        edited_list.append(BRANDS[word])
    else:
        edited_list.append(word)

A much shorter alternative would be

edited_list = [BRANDS.get(word, word) for word in sentence_list]

Either way, you can combine the edited sentence using the join method:

print(' '.join(edited_list))

This being Python, you can do the whole thing as a one-liner without using an intermediate list at all:

print(' '.join(BRANDS.get(word, word) for word in sentence_list))

Finally, you could do the joining in print itself using splat notation. Here, you would pass in each element of your list as a separate argument, and use the default sep argument to insert the spaces:

print(*edited_list)

As an aside, d = c.replace(c, BRANDS[c]) is a completely pointless equivalent of just d = BRANDS[c]. Since strings are immutable, any time you do c.replace(c, ..., you are just returning the replacent in a somewhat illegible manner.

3
  • And given that it's printing, you could avoid ' '.join entirely: print(*(BRANDS.get(word, word) for word in sentence_list)) (only real improvement is that it if the iterable contains non-strings, print will convert for you; this is mostly just an option for funsies). Aug 21, 2018 at 5:37
  • @ShadowRanger. I added something like that in. Might as well work with the full list since splat ends up storing the whole generator anyway Aug 21, 2018 at 5:40
  • True, though that same argument applies to ' '.join (which calls PySequence_Fast on the input, and therefore any non-list, non-tuple input is converted to a list up front anyway). Admittedly, in that case it's an implementation detail (it could be implemented with something like io.StringIO that they write to as they go, with expansion amortized, they just didn't). Aug 21, 2018 at 5:52
1

The problem is that print(c, end=' ') will always print a space after c. Here is a pretty minimal change to fix that:

sentence = input('Sentence: ')

sentencelist = sentence.split()
is_first = True
for c in sentencelist:
    if not is_first:
        print(' ', end='')
    is_first = False
    if c in BRANDS:
        d = c.replace(c, BRANDS[c])
        print(d, end='')
    else:
        print(c, end='')

As others have pointed out, this can be tidied up, e.g., d = c.replace(c, BRANDS[c]) is equivalent to d = BRANDS[c], and if you change it to c = BRANDS[c], then you could use a single print call and no else clause.

But you also have to be careful with your approach, because it will fail for sentences like "I bought a Hoover." The sentence.split() operation will keep "Hoover." as a single item, and that will fail the c in BRANDS test due to the extra period. You could try to separate words from punctuation, but that won't be easy. Another solution would be to apply all the replacements to each element, or equivalently, to the whole sentence. That should work fine in this case since you may not have to worry about replacement words that could be embedded in longer words (e.g., accidentally replacing 'cat' embedded in 'caterpillar'). So something like this may work OK:

new_sentence = sentence
for brand, generic in BRANDS.items():
    new_sentence = new_sentence.replace(brand, generic)
print(new_sentence)
1

Your end=' ' unconditionally appends extra spaces to your output. There is no consistent way to undo this (echoing a backspace character only works for terminals, seeking only works for files, etc.).

The trick is to avoid printing it in the first place:

sentence = input('Sentence: ')

sentencelist = sentence.split()
result = []
for c in sentencelist:
    # Perform replacement if needed
    if c in BRANDS:
        c = BRANDS[c]  # c.replace(c, BRANDS[c]) is weird way to spell BRANDS[c]
    # Append possibly replaced value to list of results
    result.append(c)

# Add spaces only in between elements, not at the end, then print all at once
print(' '.join(result))
# Or as a trick to let print add the spaces and convert non-strings to strings:
print(*result)
0

You dont have to split the word and iterating through it.

Try this code it will work and will not get the issue of white space anymore

sentence  = ' '.join(str(BRANDS.get(word, word)) for word in input_words)

Here,make a list names "input_words" and add the number of line that you wanted to process

Happy Learning!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.