用 Python 交换字符串中每对相邻字符的最简单方法是什么? [英] What is the simplest way to swap each pair of adjoining chars in a string with Python?

查看:523
本文介绍了用 Python 交换字符串中每对相邻字符的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想交换字符串中的每一对字符.'2143' 变为 '1234''badcfe' 变为 'abcdef'.

如何在 Python 中执行此操作?

解决方案

oneliner:

<预><代码>>>>s = 'badcfe'>>>''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])'abcdef'

  • s[x:x+2] 返回从 x 到 x+2 的字符串切片;对于奇数镜头来说是安全的.
  • [::-1] 在 Python 中反转字符串
  • range(0, len(s), 2) 返回 0, 2, 4, 6 ... 而 x <镜头

I want to swap each pair of characters in a string. '2143' becomes '1234', 'badcfe' becomes 'abcdef'.

How can I do this in Python?

解决方案

oneliner:

>>> s = 'badcfe'
>>> ''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])
'abcdef'

  • s[x:x+2] returns string slice from x to x+2; it is safe for odd len(s).
  • [::-1] reverses the string in Python
  • range(0, len(s), 2) returns 0, 2, 4, 6 ... while x < len(s)

这篇关于用 Python 交换字符串中每对相邻字符的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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