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.

9
  • Which engine are you using ? Commented Oct 14, 2015 at 19:30
  • why don't you use strip ? regex is'n neccesary Commented Oct 14, 2015 at 19:31
  • 1
    @PedroLobito What do you mean by engine? I am using python though, if language is what you are asking about. Commented Oct 14, 2015 at 19:32
  • 1
    @JoseRicardoBustosM. I don't know the usage of strip? Would you please elaborate? Commented Oct 14, 2015 at 19:32
  • 2
    Possible duplicate of How to trim whitespace (including tabs)? Commented Oct 14, 2015 at 19:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can you please define "this did not worked" ? what's the error ?
No error but it did not removed any whitespace and returned the same result.
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)"

Comments

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)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.