Skip to content Skip to sidebar Skip to footer

Replace A Name In A String In Python

I'm working on a assignment and I need to replace Alice with my name. Here is the program, for i in range(10): print(i) print(split_alice[i]).replace_alice('Alice','Alex')

Solution 1:

Just use replace() method on strings.. Like this

>>> mystr = 'My name is Alice'>>> mystr.replace('Alice','Alex')
'My name is Alex'

Also, if you have any doubts about anything, you should use help(). Like in your case:

>>> help(type(mystr))
Help on classstrin module __builtin__:

classstr(basestring)
 |  str(object) -> string
...
...
 |  replace(...)
 |      S.replace(old, new[, count]) -> string
 |      
 |      Return a copy of string S withall occurrences of substring
 |      old replaced by new.  If the optional argument count is
 |      given, only the first count occurrences are replaced.
 |  
...
...
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of typeobject>
 |      T.__new__(S, ...) -> a new objectwithtype S, a subtype of T

Post a Comment for "Replace A Name In A String In Python"