问题描述
嗨
我想知道是否有更好的方法来交换字符串中的前2个
字符,而不是第4个和第5个字符:
darr = list(" 010203040506")
aarr = darr [:2]
barr = darr [4:6]
darr [:2] = barr
darr [4:6] = aarr
result ="" .join(darr)
以上代码工作正常,但我想知道是否有人有另外一种
方式这样做?
A
你可以这样做:
darr = list(" 010203040506")
darr [ :2],darr [4:5] = darr [4:6],darr [:2]
result ="" .join(darr)
打印结果
Diez
假设字符串长度始终至少为5:
def swap(s):
返回''%s%s%s%s''%(s [3:6],s [2:3],s [:2],s [6:])
您可以这样做:
darr = list(" 010203040506")
darr [:2],darr [4:5] = darr [4:6],darr [:2]
result ="" .join(darr)
打印结果
Diez
这是相同的代码。我想知道字符串操作是否可以在没有进入列表世界的情况下完成。
A
Hi
I was wondering if there was a nicer way to swap the first 2
characters in a string with the 4th and 5th characters other than:
darr=list("010203040506")
aarr=darr[:2]
barr=darr[4:6]
darr[:2]=barr
darr[4:6]=aarr
result="".join(darr)
The above code works fine but I was wondering if anybody had another
way of doing this?
A
You can do it like this:
darr=list("010203040506")
darr[:2], darr[4:5] = darr[4:6], darr[:2]
result="".join(darr)
print result
Diez
Assuming the string length is always at least 5:
def swap(s):
return ''%s%s%s%s'' % (s[3:6], s[2:3], s[:2], s[6:])
You can do it like this:
darr=list("010203040506")
darr[:2], darr[4:5] = darr[4:6], darr[:2]
result="".join(darr)
print result
Diez
Thats the same code. I was wondering if the string manipulation can be
done without an excursion into the list world.
A
这篇关于替换字符串中的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!