0

Product Name:

"                Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)                  "

I have this product name in which i need to remove all the spaces before start and also after last character ")". Regex is compulsory for me. I am trying to achieve all this in python.

Note: Or lets say i need to get only the title without starting and ending spaces.

binarymason
  • 1,351
  • 1
  • 14
  • 31
Mansoor Akram
  • 1,997
  • 4
  • 24
  • 40

3 Answers3

3

Remove extra spaces using regex

There's no need to use a regex for this.

.strip() is what you need.

print yourString.strip()
#Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)

LIVE PYTHON DEMO

http://ideone.com/iEmH0i


string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
2

Well, if you must use regex, you can use this:

import re
s = "                Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)                  "
s = re.sub("^\s+|\s+$","",s)
print(s)

Result :

"Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)"

wingerse
  • 3,670
  • 1
  • 29
  • 61
1

Just for fun: a solution using regex (for this is better strip)

import re
p = re.compile('\s+((\s?\S+)+)\s+')
test_str = "                Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)                  "
subst = "\\1"

result = re.sub(p, subst, test_str)
print (result)

you get,

Samsung Floor Standing Invertor Air Conditioner - 2.0 Ton - AF-28FSSDAWKXFA (Q-9000) - White (Brand Warranty)
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62