CS50 mario python 不太舒服的 .rstrip 函数

CS50 mario python less comfortable .rstrip function

我正在学习 CS50 课程,现在我正在学习 pset6,python 马里奥代码。

对于 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


+
+
+
+
+
#


+
+
+
+
#
#


+
+
+
#
#
#


+
+
#
#
#
#


+
#
#
#
#
#

预期输出:

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

谢谢!

在打印方法中使用 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") 

它将显示:

some string
another string

根据print method documentation,我们可以使用end参数中的字符串来覆盖默认的end='\n'

例如,

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

它将显示:

some string......another string!!!!!!

参考:

您似乎想删除行尾的 \n

而不是 rstrip 使用 print("whatever you want to output in here like # or +", end = "").

rstrip 在此用例中不起作用的原因是它会剥离您传递给它的字符串,即“#”或“+”。那里没有 \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

输出:

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