Replace
Ryan Forsythe
ryan at cs.uoregon.edu
Fri May 5 21:37:53 EDT 2006
Eric wrote:
> I have a string...
>
> str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff"
>
> I want to replace the characters after each '=', what I ended up doing is
> somthing like this...
>
> buf = list(str)
> newchr = '#'
>
> count = 0
> for i in range(len(buf)):
> if buf[count] == '=':
> buf[count + 1] = newchr
> count = count + 1
> else:
> count = count + 1
>
> newstr = ''.join(buf)
So you want to turn "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" into
"tyrtrbd =#fgtyuf =# =#yryr =#=# ttttff"?
I'd probably end up writing it like you have (except the else is
redundant -- just end the test block and increment your counter in any case)
> Is there a better, faster way of doing it? Using somthing like
> str.index() dosn't work because...
>
> str = "hello world"
You don't want to use str as a variable name -- it shadows the str()
builtin:
>>> x = 1
>>> str(x)
1
>>> str = "spam"
>>> str(x)
------------------------------------------------------------
Traceback (most recent call last):
File "<console>", line 1, in ?
TypeError: 'str' object is not callable
> for i in str:
> print str.index(i)
(snip)
> Every 'e' in "hello world" has the same index value. Am i missing somthing?
Because `"hello".index("l")` returns the first place "l" appears in
"hello". It's always going to be 2.
--Ryan
More information about the Python-list
mailing list