如何一次替换字符串中的两件事? [英] How to replace two things at once in a string?

查看:39
本文介绍了如何一次替换字符串中的两件事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串,"ab".

我想将 "a" 替换为 "b" 并将 "b" 替换为 "a"一举.

所以最后,字符串应该是 "ba" 而不是 "aa""bb" 并且不要使用超过一条线.这可行吗?

解决方案

当你需要交换变量时,比如 xy,一个常见的模式是引入一个临时变量 t 帮助交换:t = x;x = y;y = t.

同样的模式也可以用于字符串:

<预><代码>>>># 交换 a 和 b>>>'obama'.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')'oabmb'

这种技术并不新鲜.它在 PEP 378 中被描述为一种在美式和欧式小数点分隔符和千位分隔符之间转换的方法(例如从 1,234,567.891.234.567,89.Guido 已经认可这是一种合理的技术.

Say I have a string, "ab".

I want to replace "a" with "b" and "b" with "a" in one swoop.

So in the end, the string should be "ba" and not "aa" or "bb" and not use more than one line. Is this doable?

解决方案

When you need to swap variables, say x and y, a common pattern is to introduce a temporary variable t to help with the swap: t = x; x = y; y = t.

The same pattern can also be used with strings:

>>> # swap a with b
>>> 'obama'.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')
'oabmb'

This technique isn't new. It is described in PEP 378 as a way to convert between American and European style decimal separators and thousands separators (for example from 1,234,567.89 to 1.234.567,89. Guido has endorsed this as a reasonable technique.

这篇关于如何一次替换字符串中的两件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆