【问题标题】:Spacing in python stringpython字符串中的间距
【发布时间】:2016-03-29 11:54:59
【问题描述】:

似乎无法弄清楚我在 python 中的间距是怎么回事。我正试图让它打印出来:

Two Vertical Lines, height=3; width=3:
* *
* *
* *

Two Vertical Lines, height=4; width=5:
*   *
*   *
*   *
*   *

Two Vertical Lines, height=5; width=2:
**
**
**
**
**

但使用此代码:

def two_vertical_lines (height, width):
    for x in range (0, height):
        if width > 2:
            new_width = width - 2 
            mult2 = " " * new_width
            print ("*",mult2,"*", "\n", end='')
        else:
             print ("**", "\n", end='')
    return

由于某种原因,我的程序正在返回:

Two Vertical Lines, height=3; width=3:
*  * 
*  * 
*  * 

Two Vertical Lines, height=4; width=5:
*  * 
*  * 
*  * 
*  * 

Two Vertical Lines, height=5; width=2:
** 
** 
** 
** 
** 

(请注意两条垂直线之间的间距/宽度差异,即使我的变量 new_width 在技术上应该是 1 个空格)

【问题讨论】:

  • 您的代码没有任何问题...我的 PyCharm 中显示的内容非常好...也许您想弄清楚打印它们的方式?

标签: python string python-3.x spacing


【解决方案1】:

默认情况下,print() 输出其参数,并用单个“”(空格)分隔。但是,这可以通过sep 参数进行更改。只需使用sep='',如下所示:

def two_vertical_lines (height, width):
    for x in range (0, height):
        if width > 2:
            new_width = width - 2 
            mult2 = " " * new_width
            print ("*", mult2, "*", sep='')  # <-- change
        else:
             print ("**", "\n", end='')
    return

【讨论】:

    【解决方案2】:

    当你使用print时,所有传递给它的参数都会被打印出来,它们之间有一个空格。

    >>> print('a', 'b')
    a b
    

    要解决这个问题,您可以创建一个字符串并打印它,像这样

    print ("*{}*\n".format(mult2), end='')
    

    其实不用在字符串中显式添加\n,可以让print函数来处理,像这样

    print ("*{}*".format(mult2))
    

    另一个改进可能是,您不必特殊情况,width &lt;= 2 情况,因为字符串与零或负整数相乘只会导致空字符串。

    >>> '*' * -1
    ''
    >>> '*' * 0
    ''
    

    所以你可以简单地写

    def two_vertical_lines(height, width):
        for x in range(height):
            print("*{}*".format(" " * (width - 2)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 2019-06-07
      • 2016-09-22
      • 2021-08-01
      • 2020-05-14
      • 1970-01-01
      相关资源
      最近更新 更多