python中的replace()字符串

2024-06-11 11:07:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我要删除“>>>;”和“…”使用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

那么,有没有人能给出一个更好的解决方案来删除“>>>;”和“…”。在


Tags: docsamjohnreplacemanagerszackjackset
3条回答

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

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

关于str.replace的帮助:

^{pr2}$

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.

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

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

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

doc = doc.replace(">>> ","").replace("...     ","")
print doc

相关问题 更多 >