相关疑难解决方法(0)

是str.replace(..).replace(..)ad令人厌恶Python中的标准习语吗?

例如,假设我想要一个函数来转义字符串以便在HTML中使用(如在Django的转义过滤器中):

    def escape(string):
        """
        Returns the given string with ampersands, quotes and angle 
        brackets encoded.
        """
        return string.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace("'", '&#39;').replace('"', '&quot;')
Run Code Online (Sandbox Code Playgroud)

这样可行,但它很快变得难看并且似乎具有较差的算法性能(在此示例中,字符串重复遍历5次).更好的是这样的事情:

    def escape(string):
        """
        Returns the given string with ampersands, quotes and angle 
        brackets encoded.
        """
        # Note that ampersands must be escaped first; the rest can be escaped in 
        # any order.
        return replace_multi(string.replace('&', '&amp;'),
                             {'<': '&lt;', '>': '&gt;', 
                              "'": '&#39;', '"': '&quot;'})
Run Code Online (Sandbox Code Playgroud)

这样的函数是否存在,或者是使用我之前编写的标准Python习惯用法?

python performance replace idioms

28
推荐指数
6
解决办法
1万
查看次数

更改字符串中其他字符的多个字符

我正在尝试操纵一个字符串。

从一个字符串中提取所有元音后,我想用同一字符串中的所有'v'替换为'b',所有'b'替换为'v'(ig“ accveioub”首先将变为ccvb,然后变为ccbv)。

我在交换字符时遇到问题。我最终得到了ccvv,我想我会根据这段代码得到它。我正在考虑遍历字符串,并使用if语句基本上停留在索引i .equals“ v”处的字符,然后将其替换为“ b”,而else语句,将“ b”替换为“ v”,然后将字符追加或合并在一起?

这是我的代码

def Problem4():
    volString = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
    s = "accveioub"
    chars = []
    index = 0

    #Removes all the vowels with the for loop
    for i in s:
        if i not in volString:
            chars.append(i)
    s2 = "".join(chars)
    print(s2)
    print(s2.replace("v", "b"))
    print(s2.replace("b", "v"))

>>> Problem4()
ccvb
ccbb
ccvv
>>> 
Run Code Online (Sandbox Code Playgroud)

python string

5
推荐指数
1
解决办法
1846
查看次数

标签 统计

python ×2

idioms ×1

performance ×1

replace ×1

string ×1