Reputation: 2441
I want to remove ">>> " and "... " form the doc using replace()
but its not working for me (it prints the same doc). Check the last three lines of code.
doc = """
>>> from sets import Set
>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
>>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
>>> employees = engineers | programmers | managers # union
>>> engineering_management = engineers & managers # intersection
>>> fulltime_management = managers - engineers - programmers # difference
>>> engineers.add('Marvin') # add element
>>> print engineers
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
>>> employees.issuperset(engineers) # superset test
False
>>> employees.update(engineers) # update from another set
>>> employees.issuperset(engineers)
True
>>> for group in [engineers, programmers, managers, employees]:
... group.discard('Susan') # unconditionally remove element
... print group
...
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
Set(['Janice', 'Jack', 'Sam'])
Set(['Jane', 'Zack', 'Jack'])
Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])
"""
doc.replace(">>> ","")
doc.replace("... ","")
print doc
So, can any one give a better solution for removing ">>> " and "... ".
Upvotes: 0
Views: 259
Reputation: 133764
Python strings are immutable so .replace
returns a new string instead of mutating the original as you have presumed.
doc = doc.replace(">>> ","").replace("... ","")
print doc
Upvotes: 1
Reputation: 251166
Strings are immutable in python, so str.replace
(and all other operations) simply return a new string and the original one is not affected at all:
doc = doc.replace(">>> ","") # assign the new string back to `doc`
doc = doc.replace("... ","")
help on str.replace
:
>>> print str.replace.__doc__
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.
Upvotes: 7
Reputation: 4746
replace()
does not modify the string, it returns a new string with the modification.
So write: doc = doc.replace(">>> ","")
Upvotes: 3