0

我想删除“>>>”和“...”形成文档,replace()但它对我不起作用(它打印相同的文档)。检查最后三行代码。

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

那么,任何人都可以为删除“>>>”和“...”提供更好的解决方案。

4

3 回答 3

7

字符串在 python 中是不可变的,因此str.replace(以及所有其他操作)只需返回一个新字符串,而原始字符串根本不受影响:

doc = doc.replace(">>> ","")      # assign the new string back to `doc`
doc = doc.replace("...     ","")

帮助str.replace

>>> print str.replace.__doc__
S.replace(old, new[, count]) -> string

返回字符串 S 的副本,其中所有出现的子字符串 old 都替换为 new。如果给定了可选参数 count,则仅替换第一个 count 出现。

于 2013-06-16T10:34:29.000 回答
3

replace()不修改字符串,它返回一个带有修改的新字符串。

所以写:doc = doc.replace(">>> ","")

于 2013-06-16T10:34:36.373 回答
1

Python 字符串是不可变的,因此.replace返回一个新字符串,而不是像您假设的那样改变原始字符串。

doc = doc.replace(">>> ","").replace("...     ","")
print doc
于 2013-06-16T10:34:27.007 回答