【问题标题】:Inverting symbols in python 3.xpython 3.x中的反转符号
【发布时间】:2017-02-26 17:31:58
【问题描述】:

我有一个字符串:

a = '3+7-9'

我需要将'+' 转换为'-''-' 转换为'+' 才能得到

a = '3-7+9'

使用 而不乘以* -1 的正确方法是什么?

【问题讨论】:

  • *-1 相乘将不起作用。这是一个字符串。您不能将字符串与负数相乘(它会生成空字符串)。

标签: python-3.x string python-3.x str-replace


【解决方案1】:

您可以使用str.translate(..) 并使用str.maketrans(..) 构建地图:

a = a.translate(str.maketrans("+-","-+"))

str.maketrans("+-","-+") 将构造一个字典:

>>> str.maketrans("+-","-+")
{43: 45, 45: 43}

因此它将带有代码43(即'+')的字符映射到字符45(即'-')上,反之亦然。

因此,您可以通过省略str.maketrans(..) 部分并写入来稍微提高性能:

a = a.translate({43: 45, 45: 43})

这会生成:

>>> a = '3+7-9'
>>> a.translate({43: 45, 45: 43})
'3-7+9'

如果您知道 Linux 的 tr 命令,您会注意到:

a.translate(str.maketrans("<i>x</i>","<i>y</i>"))

相当于:

tr <i>x</i> <i>y</i>

(在 Linux 外壳中)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    相关资源
    最近更新 更多