0

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 "... ".

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

although this answer solves the OP's particular problem, in general replace is a wrong tool for that (think >>> print ">>>foo").
3

replace() does not modify the string, it returns a new string with the modification.

So write: doc = doc.replace(">>> ","")

Comments

1

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

1 Comment

@BurhanKhalid Ok fixed but I would have changed it happily without the DV ;) Also you are always free to edit things such as that in. IIRC that is not a valid reason to downvote since my answer is and was useful but no hard feelings here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.