[Tutor] Finding and replacing a space in a string.

Karl Pflästerer sigurd at 12move.de
Wed Jan 28 17:15:16 EST 2004


On 28 Jan 2004, Brian Connelly <- brian at connellyman.com wrote:

> My problem is that row[1] or ID is 6 characters or less and in some
> casses it has a ' ' space which i need to replace with a '-' and if it
> does not have a space I would like to leave it alone.

> Any sugestions ?

> for example:

>>>> id 'ZURE A'

> newid should become 'ZURE-A'

> and if id = 'WHITO' newid = 'WHITO'

If it's so simple you can use the `replace' method of strings.
E.g.:

>>> s = "I am a string with space"
>>> s = s.replace(' ', '-')
>>> s
'I-am-a-string-with-space'
>>> 

If you wanted only the first occurence to be replaced you could write:

>>> s = "I am a string with space"
>>> s = s.replace(' ', '-', 1)
>>> s
'I-am a string with space'
>>> 

If there are no spaces in the string nothing happens.

>>> s = "foo"
>>> s = s.replace(' ', '-', 1)
>>> s
'foo'
>>> 


What helped me a lot when I started using Python was using the
interactive read-eval-print-loop (REPL).  If I didn't knew what methods
a class had I simply typed:

>>> s = "foo"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> 

Now I read replace which looks promising but I don't know what it does;
but I can ask Python.  So I type:

>>> help(s.replace)
Help on built-in function replace:

replace(...)
    S.replace (old, new[, count]) -> string
    
    Return a copy of string S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.
(END) 




   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list