| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
- #/ -*- coding:utf-8 -*-
 
 - s=input()
 
 - i=0
 
 - j=0
 
 - len=len(s)
 
  
- str0=[0]*len
 
 -         
 
 - while(i<len):
 
 -     if(s[i].isalpha()):
 
 -             if(65<=ord(s[i]) and ord(s[i])<=77):
 
 -                 temp1=ord(s[i])
 
 -                 temp2=ord('Z')-(temp1-ord('A'))
 
 -                 str0[i]=s[i].replace(s[i],str(temp2))
 
 -                 str0[i]=chr(int(str0[i]))
 
 -                 i+=1
 
 -             elif(78<=ord(s[i]) and ord(s[i])<=90):
 
 -                 temp1=ord(s[i])
 
 -                 temp2=ord('A')+(ord('Z')-temp1)
 
 -                 str0[i]=s[i].replace(s[i],str(temp2))
 
 -                 str0[i]=chr(int(str0[i]))
 
 -                 i+=1
 
 -             elif(97<=ord(s[i]) and ord(s[i])<=109):
 
 -                 temp1=ord(s[i])
 
 -                 temp2=ord('z')-(temp1-ord('a'))
 
 -                 str0[i]=s[i].replace(s[i],str(temp2))
 
 -                 str0[i]=chr(int(str0[i]))
 
 -                 i+=1
 
 -             elif(110<=ord(s[i]) and ord(s[i])<=122):
 
 -                 temp1=ord(s[i])
 
 -                 temp2=ord('a')+(ord('z')-temp1)
 
 -                 str0[i]=s[i].replace(s[i],str(temp2))
 
 -                 str0[i]=chr(int(str0[i]))
 
 -                 i+=1
 
 -             else:
 
 -                 i+=1
 
 -     else:
 
 -         str0[i]=s[i] 
 
 -         i+=1
 
 - for test in str0:
 
 -     print(test,end='')
 
  
  复制代码 
 
 
输入: 
期望输出:中文保留,英文字符进行反码 
实际输出: 
 
求大佬解答其中原因!!!
这段代码的目的是将输入的字符串中的英文字符进行反码处理,保留中文字符不变。 
 
问题出在对于英文字符的反码处理上。代码中使用了replace()方法来替换字符,然后再将替换后的字符串转换为整数,最后再转换为字符。这样的处理方式是不正确的。 
 
正确的处理方式是使用ord()函数获取字符的ASCII码,然后根据ASCII码进行反码处理,最后再将反码转换为字符。 
 
以下是修正后的代码: 
 
- s = input()
 
 - str0 = []
 
  
- for ch in s:
 
 -     if ch.isalpha():
 
 -         if 'A' <= ch <= 'M':
 
 -             temp1 = ord(ch)
 
 -             temp2 = ord('Z') - (temp1 - ord('A'))
 
 -             str0.append(chr(temp2))
 
 -         elif 'N' <= ch <= 'Z':
 
 -             temp1 = ord(ch)
 
 -             temp2 = ord('A') + (ord('Z') - temp1)
 
 -             str0.append(chr(temp2))
 
 -         elif 'a' <= ch <= 'm':
 
 -             temp1 = ord(ch)
 
 -             temp2 = ord('z') - (temp1 - ord('a'))
 
 -             str0.append(chr(temp2))
 
 -         elif 'n' <= ch <= 'z':
 
 -             temp1 = ord(ch)
 
 -             temp2 = ord('a') + (ord('z') - temp1)
 
 -             str0.append(chr(temp2))
 
 -         else:
 
 -             str0.append(ch)
 
 -     else:
 
 -         str0.append(ch)
 
  
- result = ''.join(str0)
 
 - print(result)
 
 
  复制代码 
 
这样修改后,输入 "学好Python,用Coding建设祖国",输出结果为 "学好Kbgslm,用Xlwrmt建设祖国",符合预期的结果。 
 
 
 |   
 
 
 
 |