String Handling

Skip Montanaro skip at mojam.com
Tue Jan 4 16:29:15 EST 2000


    Simon> Can anyone give me the Python line/command to change all spaces
    Simon> in a string to +s?

Taking a slightly different tack than the other respondents, I'll presume
with no real evidence that you are quoting strings for use in URLs (that's
the only other place I have seen space-to-plus conversions).

*If* that's the case, you probably want to use urllib.quote_plus:

    >>> import urllib
    >>> urllib.quote_plus("Can't we *ever* agree on anything?")
    'Can%27t+we+%2aever%2a+agree+on+anything%3f'

If you can tolerate (or want) %20 instead of +, use urllib.quote:

    >>> urllib.quote("Can't we *ever* agree on anything?")
    'Can%27t%20we%20%2aever%2a%20agree%20on%20anything%3f'

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list