在学校为作业分配字符打印机时遇到了一些问题,尽管在StackOverflow上到处都看不到如何解决它。我试图使用户能够输入他们想要的前两行顶行和底行的符号,并根据字长将其两个文本的正反斜线居中。但是,这已被证明是一个问题。
我试图更改变量以及创建将文本长度封装为整数的变量,但事实证明这是不成功的。
Repeats = input("How many times should the symbol repeat (1-30 CHARACTERS)?:")
insertText = input("Please enter text:")
insertText = str(insertText)
insertMoreText =input("Please enter text (again):")
insertMoreText= str(insertMoreText)
Repeats = int(Repeats)
#Determining text lengths/stored variables:
text1length = len(insertText)
text2length = len(insertMoreText)
forwardSlash = str("/")
backSlash = str("\\")
symbolsbeforeText = "*"
if(Repeats <= 30):
print(firstSymbol * Repeats)
print(secondSymbol * Repeats)
print(symbolsbeforeText * Repeats)
print (forwardSlash * text1length) & (insertText.upper()) & (forwardSlash
* text1length)
print (backSlash * text2length) + (insertMoreText.lower()) + (backSlash *
text2length)
print(symbolsbeforeText * Repeats)
print(secondSymbol * Repeats)
print(firstSymbol * Repeats)
else:
print("You have reached the repetition threshold, please try again.")
错误:
Traceback (most recent call last):
File "C:\Users\colby\trainingTime.py", line 28, in <module>
print (forwardSlash * text1length) & (insertText.upper()) &
(forwardSlash * text1length)
TypeError: unsupported operand type(s) for &: 'NoneType' and 'str'
Process terminated with an exit code of 1
答案 0 :(得分:2)
#!/bin/bash
function debug() {
echo "it is debugging"
"$@"
}
function first() {
echo "doing some first stuff"
}
function second() {
echo "doing some second stuff"
}
debug first
debug second
echo "doing main stuff"
函数始终返回print
,并且您正在执行返回值None
和print
(这是一个字符串)的按位与运算。导致上述错误。
您应该使用整个括号内的整个表达式作为参数来调用(insertText.upper())
:
print
答案 1 :(得分:1)
您的问题是在Python 3+中,print是一个返回None
的函数,所以:
print(forwardSlash * text1length)
返回None
和
insertText.upper()
返回一个str
。因此,您无法在&
和None
上执行逐位str
操作。
解决此问题的一种非常好的方法是使用f字符串,这是自Python 3.6起可用的Python功能:
print(f"{backSlash * text2length} {insertMoreText.lower()} {backSlash * text2length}")
这将使您的代码更具可读性。看到您不需要使用+
连接字符串,这可能会引起您的困惑。