-4

I have manufacture name and a product name which has manufacture name and I want to remove manufacture name form product name, I use the following code but didn't work

I tried both sub and replace methods but didn't work

import re

menufacture_name = "AMPHENOL ICC (COMMERCIAL PRODUCTS)"

product_name = "AMPHENOL ICC (COMMERCIAL PRODUCTS) - D-SUB CONNECTOR, PLUG, 9POS"

// product_name = re.sub(menufacture_name + " - ", "", product_name)
product_name.replace(menufacture_name + " - ", '')

print("Product name : " + product_name)

This should be the result Product name : D-SUB CONNECTOR, PLUG, 9POS

Minhaj Javed
  • 595
  • 5
  • 18

3 Answers3

1

replace doesn't replace the current string. It will return a copy of the modified string.

Note: In Python strings are immutable.

Try like below:

modified_string = product_name.replace(menufacture_name + " - ", '')

print("Product name : " + modified_string)
Jay
  • 23,225
  • 23
  • 88
  • 135
1

Here's one way to do it, you just have to assign the result of the replace, because the original string is not modified in-place (strings are immutable in Python, so all string operations return a new one instead):

product_name = product_name.replace(menufacture_name, "").strip("- ")

product_name
=> 'D-SUB CONNECTOR, PLUG, 9POS'

Notice that I used strip() to remove the extra "- " characters from one side, so the output string will look nicer.

Óscar López
  • 225,348
  • 35
  • 301
  • 374
1

Strings are immutable. Your code is correct just that you forgot to assign the replace back to the string.

product_name = product_name.replace(menufacture_name + " - ", '')

This should work.

Mayank Porwal
  • 31,737
  • 7
  • 30
  • 50