【问题标题】:Replacing characters in a string and returning in python替换字符串中的字符并在python中返回
【发布时间】:2015-07-13 16:22:46
【问题描述】:

我使用 Pycharm 作为软件工具在 python 中编写代码。

这些词是文本格式,但它们应该返回不同的输出

word = "<p>Santa is fat</p>"
secondword = "Potato & Tomato"
thirdword = "Koala eats http://koala.org/ a lot</p>"

我想将以下每个 "" , "&" 替换为 "&amp;lt;" , "&amp;gt;" , "&amp;amp;"

所以输出应该是这样的

outputword = "&lt;p&gt;Santa is fat&lt;/p&gt;"
outputsecondword = "Fish &amp; Chips"
outputthirdword = ""&lt;p&gt;Koala eats <a href='http://koala.org/'>http://koala.org/</a> a lot&lt;/p&gt;"

请注意,第三个单词是 URL。 我不想使用 html 库。 我是 Python 的菜鸟,所以请为我提供简单的解决方案。我考虑过使用列表,但每当我替换列表中的一个字符时,它都不会改变

【问题讨论】:

  • 请注意,HTML 实体是 '&amp;gt;''&amp;lt;'...
  • 当你说“我考虑过使用列表,但是每当我替换列表中的一个字符时,它并没有改变”,这并不能解释你的尝试足以让任何人解释你做了什么错误的。也许你离正确的只有一个错字;也许你完全走错了方向——如果你给我们看代码,我们可以告诉你。

标签: python string list replace


【解决方案1】:

不使用html 库,您可以像这样进行替换:

replacewith = {'<':'lt;', '>':'gt;'}
for w in replacewith:
        word = word.replace(w,replacewith[w])

In [407]: word
Out[407]: 'lt;pgt;Santa is fatlt;/pgt;'

或者,在一行中:

 word.replace('<','lt;').replace('>','gt;')

更新:

您可以将代码移动到一个函数中并像这样调用它:

def replace_char(word, replacewith=replacewith):
    for w in replacewith:
            word = word.replace(w,replacewith[w])
    return word

像下面这样用word 调用它会给你:

replace_char("<p>Santa is fat</p>")
Out[457]: 'lt;pgt;Santa is fatlt;/pgt;'

要让第二个工作,更新字典:

In [454]: replacewith.update({'Potato':'Fish', 'Tomato':'Chips', '&': '&amp;',})
In [455]: replace_char("Potato & Tomato", replacewith)
Out[455]: 'Fish &amp; Chips'

您可以以几乎相同的方式对可能出现在其他新字符串中的任何新字符执行相同的操作。您的输入 thirdword 在开头缺少 &lt;p&gt;

In [461]: replacewith.update({'http://koala.org/':'<a href="http://koala.org/">http://koala.org/</a>'})
In [463]: replace_char("Koala eats http://koala.org/ a lot</p>", replacewith)
Out[463]: 'Koala eats lt;a href="http://koala.org/"gt;http://koala.org/lt;/agt; a lotlt;/pgt;'

【讨论】:

  • 为什么要进行if w in word: 测试?如果这应该是一种优化,那么您实际上所做的就是强制它线性搜索word 两次而不是一次……
  • 另外,为什么replacewith.get(w) 而不仅仅是replacewith[w]
  • 给我一点时间,让我试试这个。
  • @abarnert 感谢您的评论。修复了两者。无意的“错别字”,两者都有。
  • 这是一个dictionary@Manu。
【解决方案2】:

Python 来了with batteries included:

import html

word = "<p>Santa is fat</p>"
print(html.escape(word))

输出:

&lt;p&gt;Santa is fat&lt;/p&gt;

【讨论】:

  • 赞成不回答他的问题,而是回答他想要/需要的内容。
  • @RvdK 谢谢你:)
  • 不使用“import html”怎么办
  • 你不会的。使用 Python 提供的库。以防万一您的下一个问题是如何使用正则表达式解析 HTML:您也不需要。
  • 基本replace方法:s = 'abcdef's = s.replace('e', 'g')s&gt;&gt; 'abcdgf'
猜你喜欢
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 2016-08-03
  • 2012-04-23
  • 2014-07-08
  • 2011-01-11
  • 2014-03-17
  • 2017-05-03
相关资源
最近更新 更多