【发布时间】:2022-01-09 12:21:14
【问题描述】:
考虑以下示例:
string_now = 'apple and avocado'
stringthen = string_now.swap('apple', 'avocado') # stringthen = 'avocado and apple'
和:
string_now = 'fffffeeeeeddffee'
stringthen = string_now.swap('fffff', 'eeeee') # stringthen = 'eeeeefffffddffee'
Swap character of string in Python 中讨论的方法不起作用,因为那里使用的映射技术只考虑了一个字符。 Python 的内置str.maketrans() 也只支持单字符翻译,当我尝试做多字符时,它会抛出以下错误:
replace() 方法链不仅远非理想(因为我有很多替换要做,链接替换将是一大块代码),而且由于它的顺序性,它不能完美地翻译为:
string_now = 'apple and avocado'
stringthen = string_now.replace('apple','avocado').replace('avocado','apple')
给出'apple and apple' 而不是'avocado and apple'。
实现这一目标的最佳方法是什么?
【问题讨论】:
-
是否有保证不在字符串中的字符?例如
\n? -
'applemon'.swap('apple', 'lemon')应该生产什么? -
@KellyBundy 这是一个有趣的案例,但对于我的案例来说,不会有这样的案例。它们重叠的地方。它可以是
'applemon'.swap('apple', 'mon')或'applemon'.swap('app', 'lemon')。但这肯定是一个非常有趣的案例。 -
没有永远不会出现的角色。尤其是新行几乎总是出现在多句行中
-
python-ideas 上的旧消息 :-)
标签: python python-3.x string