CS50 mario python不太舒适的.rstrip功能

时间:2020-07-13 20:02:35

标签: python cs50

我正在上CS50课程,现在我正在使用pset6(Python Mario代码)

对于rstrip()函数,应该在代码末尾删除新行。我不知道发生了什么,它真的困扰着我(我认为这是语法错误,但我不确定)。

如果有什么可以帮助的,那就太好了!

注意:我使用“ +”符号表示“”只是为了个人理解。

我的代码:

def input_number(message):
    while True:
        try:
            user_input = int(input(message))
        except ValueError:
            continue
        else:
            return user_input



height = input_number("Height: ")
while height < 1 or height > 8:
    height = int(input("Height: "))


i = 0
while i < height:
    print("\n")
    x = height-1
    a = 0
    while x>=i:
        print("+".rstrip("\n"))
        x-=1

    while a<=i:
        print("#".rstrip("\n"))
        a+=1

    i+=1
#print("\n")

打印什么:

Height: 5


+
+
+
+
+
#


+
+
+
+
#
#


+
+
+
#
#
#


+
+
#
#
#
#


+
#
#
#
#
#

预期输出:

    #
   ##
  ###
 ####
#####

谢谢!

2 个答案:

答案 0 :(得分:3)

在打印方法中使用function1().then(() => { function2().then(() => { function3().then(() => { }) }) }).catch((err) => { console.log(err); }) ,而不是end=""方法。

rstrip

输出:

def input_number(message):
    while True:
        try:
            user_input = int(input(message))
        except ValueError:
            continue
        else:
            return user_input



height = input_number("Height: ")
while height < 1 or height > 8:
    height = int(input("Height: "))


i = 0
while i < height:
    x = height-1
    a = 0
    while x>=i:
        print(" ", end="")
        x-=1
    while a<=i:
        print("#", end="")
        a+=1
    print("")
    i+=1

说明:

Height: 5 # ## ### #### ##### 用于删除字符串末尾的空格。例如,当我们想从用户输入的字符串中删除不需要的空格时,可以使用rstrip来删除。 rstrip的另一个用例是在读取文件时省略行中的空格。

另一方面,为了将输出字符串格式化为所需的格式,我们操纵rstrip方法。默认情况下,print方法在单独的行中输出值。

例如,

print

它将显示:

print("some string") 
print("another string") 

根据print method documentation,我们可以在some string another string 参数中使用字符串来覆盖默认的end

例如,

end='\n'

它将显示:

print("some string", end="......") 
print("another string", end="!!!!!!") 

参考:

答案 1 :(得分:1)

您似乎想删除行末的hand = [threehearts]

代替rstrip使用 \n

在此用例中rstrip无法使用的原因是,它将剥离您传递给它的字符串“#”或“ +”。这里没有print("whatever you want to output in here like # or +", end = ""),它被添加为打印的结束字符。

\n

输出:

def input_number(message):
    while True:
        try:
            user_input = int(input(message))
        except ValueError:
            continue
        else:
            return user_input



height = input_number("Height: ")
while height < 1 or height > 8:
    height = int(input("Height: "))


i = 0
while i < height:
    print("")
    x = height-1
    a = 0
    # while x>=i:
    #     print("+", end = "")
    #     x-=1

    while a<=i:
        print("#", end = "")
        a+=1

    i+=1