仅使用索引和循环,如何在字符串中交换相邻字符的位置,同时将空格设置为例外?
I/P:你好
O/P: EHLLO OWLRD
这就是我写的代码:
s1=''
for j in range(0,len(s)-1,2):
if(skip==1):
print()
skip=0
elif(s[j].isspace()==False and s[j+1].isspace()==False):
s1=s1+s[j+1]+s[j]
elif(s[j].isspace()==False and s[j+1].isspace()==True):
s1=s1+s[j]+" "
elif(s[j].isspace()==True and s[j+1].isspace()==False and s[j+2].isspace()==False):
s1=s1+" "+s[j+2]+s[j+1]
skip=1
elif(s[j].isspace()==True and s[j+1].isspace()==False and s[j+2].isspace()==True):
s1=s1+" "+s[j+1]
print("new string is",s1)我到底在做什么错事?
发布于 2022-08-29 16:50:26
inp = "HELLO WORLD"
expected = "EHLLO OWLRD"
for i in range(0, len(inp), 2): # iterate in steps of two
# check to make sure that we are not at end of string and charaters are not spaces
if i+1 < len(inp) and inp[i] != " " and inp[i+1] != " ":
# now do the string replacing
temp1 = inp[i]
temp2 = inp[i + 1]
inp = inp[:i] + temp2 + temp1 + inp[i+2:]
# output to indicate the new string is what we expect
print(inp)
print(expected)
print(inp == expected)发布于 2022-08-29 19:30:31
另一种解决办法是:
s = "HELLO WORLD"
out = []
for w in map(list, s.split(" ")):
for i in range(1, len(w), 2):
w[i], w[i - 1] = w[i - 1], w[i]
out.append("".join(w))
print(" ".join(out))指纹:
EHLLO OWLRDhttps://stackoverflow.com/questions/73531986
复制相似问题