python中的replace()字符串

bkm*_*ron 0 python string replace

我想删除">>>"和"..."形式的文档,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
Run Code Online (Sandbox Code Playgroud)

因此,任何人都可以为删除">>>"和"......"提供更好的解决方案.

Ash*_*ary 7

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

doc = doc.replace(">>> ","")      # assign the new string back to `doc`
doc = doc.replace("...     ","")
Run Code Online (Sandbox Code Playgroud)

帮助str.replace:

>>> print str.replace.__doc__
S.replace(old, new[, count]) -> string
Run Code Online (Sandbox Code Playgroud)

返回字符串S 的副本,其中所有出现的substring old都替换为new.如果给出可选参数计数,则仅替换第一次计数.