Reputation: 2056
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.
Upvotes: 0
Views: 118
Reputation: 3796
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)"
Upvotes: 2
Reputation: 8164
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)
Upvotes: 1
Reputation: 98921
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
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.
Upvotes: 3