首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python中的索引和循环来交换字符串中相邻字符的位置

使用Python中的索引和循环来交换字符串中相邻字符的位置
EN

Stack Overflow用户
提问于 2022-08-29 16:41:04
回答 2查看 86关注 0票数 1

仅使用索引和循环,如何在字符串中交换相邻字符的位置,同时将空格设置为例外?

I/P:你好

O/P: EHLLO OWLRD

这就是我写的代码:

代码语言:javascript
复制
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)

我到底在做什么错事?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-08-29 16:50:26

代码语言:javascript
复制
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)
票数 0
EN

Stack Overflow用户

发布于 2022-08-29 19:30:31

另一种解决办法是:

代码语言:javascript
复制
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))

指纹:

代码语言:javascript
复制
EHLLO OWLRD
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73531986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档