python - 代码抛出错误:只能将 str(不是“NoneType”)连接到 str
问题描述
它似乎在为空时可能正在运行S
,但它不应该因为我的第if
一句话。
它在第 15 行抛出错误:只能将str
(不是“NoneType”)连接到str
.
def encipher(S, n):
"""
Returns a forward shifted string based on the rules of caesar cipher
Argument S: String to be shifted
Argument n: number of spaces shifted
"""
if len(S) > 0:
if ord("a")<=ord(S[0])<=ord("z"): #lowercase letters
if ord("a") <= ord(S[0])+n <= ord("z"): #if the shifter letter is in the alphabet range add
return rot(S[0],n) + encipher(S[1:],n)
else: #else subtract
return rot(S[0],(n-26)) + encipher(S[1:],n)
elif ord("A")<=ord(S[0])<=ord("Z"): #uppercase letters
if ord("A") <= ord(S[0])+n <= ord("Z"): #if the shifter letter is in the alphabet range add
return rot(S[0],(n)) + encipher(S[1:],n)
else: #else subtract
return rot(S[0],(n-26)) + encipher(S[1:],n)
else:
return S[0] + encipher(S[1:],n)
else:
return
def rot(c, n):
#shifts a character
if len(c)>0:
return chr(ord(c)+n)
else:
return
解决方案
只需None
将它们更改为 string( ""
) 就可以了。
def encipher(S, n):
"""
Returns a forward shifted string based on the rules of caesar cipher
Argument S: String to be shifted
Argument n: number of spaces shifted
"""
if len(S) > 0:
if ord("a") <= ord(S[0]) <= ord("z"): # lowercase letters
if ord("a") <= ord(S[0]) + n <= ord("z"): # if the shifter letter is in the alphabet range add
return rot(S[0], n) + encipher(S[1:], n)
else: # else subtract
return rot(S[0], (n - 26)) + encipher(S[1:], n)
elif ord("A") <= ord(S[0]) <= ord("Z"): # uppercase letters
if ord("A") <= ord(S[0]) + n <= ord("Z"): # if the shifter letter is in the alphabet range add
return rot(S[0], (n)) + encipher(S[1:], n)
else: # else subtract
return rot(S[0], (n - 26)) + encipher(S[1:], n)
else:
return S[0] + encipher(S[1:], n)
else:
return ""
def rot(c, n):
# shifts a character
if len(c) > 0:
return chr(ord(c) + n)
else:
return ""
S = "b"
n = 3
print(encipher(S, n))
输出:
e
推荐阅读
- kotlin - 如何在 kotlin 中调用接口?
- mysql - mysql for Postgresql中PATINDEX的熟悉功能
- python - 从文本文件的每一行中提取字符串并将输出保存在 csv 行中
- angular - 如何修复“找不到模块'@angular-devkit/schematics'”
- javascript - 如何在午夜或基本上在 Javascript 中的新一天更新当前日期
- docker - 从 docker 容器安装 boto3
- java - 引导样式不起作用(不折叠)
- linux - 如何永久设置 GOPATH 环境变量
- c# - 在构建后事件之前或之后使用强名称对程序集进行签名?
- java - 为什么 urlConnection.getContentType() 为从 url 读取的某些图像提供 null 值?