我想要交换字符串中每一对字符的位置。例如将
在Python中要如何实现?
'2143'
变为'1234'
,将'badcfe'
变为'abcdef'
。在Python中要如何实现?
一行代码:
>>> s = 'badcfe'
>>> ''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])
'abcdef'
a, b = b, a
在我看来,您只需要使用扩展切片来完成相同的操作。但是,由于字符串是不可变的,所以这会稍微复杂一些;因此,您需要将其转换为列表,然后再转回字符串。
因此,我会按照以下方式处理:
>>> s = 'badcfe'
>>> t = list(s)
>>> t[::2], t[1::2] = t[1::2], t[::2]
>>> ''.join(t)
'abcdef'
>>> s = '2134'
>>> def swap(c, i, j):
... c = list(c)
... c[i], c[j] = c[j], c[i]
... return ''.join(c)
...
>>> swap(s, 0, 1)
'1234'
>>>
''.join(s[i+1]+s[i] for i in range(0, len(s), 2)) # 10.6 usec per loop
或者
''.join(x+y for x, y in zip(s[1::2], s[::2])) # 10.3 usec per loop
''.join(x+y for x, y in itertools.izip_longest(s[1::2], s[::2], fillvalue=''))
s='0123456789'*4
。IndexError: string index out of range
错误,第二个将删除最后一个字符。 - Paulo Scardine如果性能或优雅并不是问题,你只需要清晰明了的完成任务,那么可以使用以下代码:
def swap(text, ch1, ch2):
text = text.replace(ch2, '!',)
text = text.replace(ch1, ch2)
text = text.replace('!', ch1)
return text
这允许你交换或替换字符或子字符串。例如,要在文本中交换 'ab' <-> 'de':
_str = "abcdefabcdefabcdef"
print swap(_str, 'ab','de') #decabfdecabfdecabf
不需要列出清单。以下适用于长度为偶数的字符串:
r = ''
for in in range(0, len(s), 2) :
r += s[i + 1] + s[i]
s = r
按两个字符为一组循环遍历字符串并交换:
def oddswap(st):
s = list(st)
for c in range(0,len(s),2):
t=s[c]
s[c]=s[c+1]
s[c+1]=t
return "".join(s)
提供:
>>> s
'foobar'
>>> oddswap(s)
'ofbora'
对于奇数长度的字符串,会出现IndexError异常。
要交换字符串a中位置l和r的字符
def swap(a, l, r):
a = a[0:l] + a[r] + a[l+1:r] + a[l] + a[r+1:]
return a
例子: swap("aaabcccdeee", 3, 7) 返回 "aaadcccbeee"
# item can be a string or tuple and swap can be a list or tuple of two
# indices to swap
def swap_items_by_copy(item, swap):
s0 = min(swap)
s1 = max(swap)
if isinstance(item,str):
return item[:s0]+item[s1]+item[s0+1:s1]+item[s0]+item[s1+1:]
elif isinstance(item,tuple):
return item[:s0]+(item[s1],)+item[s0+1:s1]+(item[s0],)+item[s1+1:]
else:
raise ValueError("Type not supported")
>>> swap_items_by_copy((1,2,3,4,5,6),(1,2))
(1, 3, 2, 4, 5, 6)
>>> swap_items_by_copy("hello",(1,2))
'hlelo'
>>>
def revstr(a):
b=''
if len(a)%2==0:
for i in range(0,len(a),2):
b += a[i + 1] + a[i]
a=b
else:
c=a[-1]
for i in range(0,len(a)-1,2):
b += a[i + 1] + a[i]
b=b+a[-1]
a=b
return b
a=raw_input('enter a string')
n=revstr(a)
print n