Evaluate string from user to comma separated words string
Let's say I have a string given by user in the following fo开发者_开发百科rm:
"single, single, double word, single word, also single"
How I can parse this string to obtain string of comma separated words, where each not single whitespace is treated as a separator and replaced with ','
, and each single is replaced with %20
? So the result would be:
"single,single,double%20word,single,word,also,single"
? can I do it in one step ?
This does what you ask:
def repl(m):
if m.group(0) == ' ':
return '%20'
else:
return ','
re.sub(',? +', repl, "single, single, double word, single word, also single")
However, if your goal is to end up with proper URL escaping I'd advise that you actually use a library function designed to do that. eg: urllib.quote
You probably could do it in a single step, but it would be safer to do it in two.
First use a regex to replace \s\s+
with ,
Then replace \s
with %20
精彩评论