Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以固定宽度打印字符串?_Python_Python 3.x_Python 2.7_Format - Fatal编程技术网

Python 如何以固定宽度打印字符串?

Python 如何以固定宽度打印字符串?,python,python-3.x,python-2.7,format,Python,Python 3.x,Python 2.7,Format,我有这个代码(打印字符串中所有排列的出现) 我想打印字符串变量中的所有置换事件 由于排列的长度不同,我想固定宽度,并以漂亮的字体打印,而不是像这样: value a - num of occurrences = 1 value ab - num of occurrences = 1 value abc - num of occurrences = 1 value b - num of occurrences = 1 value bc - num of

我有这个代码(打印字符串中所有排列的出现)

我想打印字符串变量中的所有置换事件

由于排列的长度不同,我想固定宽度,并以漂亮的字体打印,而不是像这样:

value   a - num of occurrences =    1
value   ab - num of occurrences =    1
value   abc - num of occurrences =    1
value   b - num of occurrences =    1
value   bc - num of occurrences =    1
value   bcd - num of occurrences =    1
value   c - num of occurrences =    1
value   cd - num of occurrences =    1
value   d - num of occurrences =    1
如何使用
格式
执行此操作

我找到了这些帖子,但与字母数字字符串不太匹配:


编辑2013-12-11-这个答案非常古老。它仍然是有效的和正确的,但是人们应该更喜欢这个

您可以这样使用:

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa
基本上:

  • %
    字符通知python它必须将某些内容替换为令牌
  • s
    字符通知python标记将是字符串
  • 5
    (或任何您想要的数字)通知python在字符串中填充最多5个字符的空格
在您的特定情况下,可能的实现如下所示:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1
旁注:我只是想知道你是否意识到这个问题的存在。例如,您可以通过以下方式在一行中获得所有组合的列表:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

通过使用
组合
count()

结合使用
str.format
我发现使用
str.format
更优雅:

>>> '{0: <5}'.format('s')
's    '
>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'

编辑1: 正如评论中提到的:{0:中的
0
最初是作为@0x90答案的编辑发布的,但由于偏离了帖子的初衷而被拒绝,并建议作为评论或答案发布,所以我在这里包括了这篇短文

除了@0x90的答案外,还可以通过使用宽度变量(根据@user2763554的注释),使语法更加灵活:

或者,对于最大的、潜在的非pythonical隐式紧性,甚至忽略所有数字:

width=10
'{: <{}}'.format('sss', width)
这也适用于字符串格式

>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '
宽度=10 >>>字符串='sss'
>>>f'{string:
格式
无疑是最优雅的方式,但您不能将其与python的
日志记录
模块一起使用,因此下面介绍如何使用
%
格式:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)
这里,
-
表示左对齐,
s
前面的数字表示固定宽度

一些示例输出:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

更多信息请参见此处的文档:

>print(f“{'123':当您希望在一个print语句中打印多个元素时,这将有助于保持固定长度

25s
格式化带有25个空格的字符串,默认情况下左对齐

5d
格式化一个保留5个空格的整数,默认情况下右对齐

members=[“Niroshan”、“Brayan”、“Kate”]
打印(“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
打印({:25s}{:32s}{:35s})。格式(“姓名”、“国家”、“年龄”))
打印(“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
打印({:25s}{:30s}{:5d})。格式(成员[0],“斯利兰卡”,20))
印刷品({:25s}{:30s}{:5d})。格式(成员[1],“澳大利亚”,25))
印刷品({:25s}{:30s}{:5d})。格式(成员[2],“英格兰”,30))
打印(“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
这个会打印出来

__________________________________________________________________
Name                      Country                          Age
__________________________________________________________________
Niroshan                  Srilanka                          20
Brayan                    Australia                         25
Kate                      England                           30
__________________________________________________________________
我发现
ljust()
rjust()
以固定宽度或宽度打印字符串非常有用

一个例子

print('123.00'.rjust(9))
print('123456.89'.rjust(9))

# expected output  
   123.00
123456.89
对于您的案例,您可以使用
fstring
打印案例

for prefix in unique:
    if prefix != "":
        print(f"value  {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")
预期产量

value  a   - num of occurrences = 1
value  ab  - num of occurrences = 1
value  abc - num of occurrences = 1
value  b   - num of occurrences = 1
value  bc  - num of occurrences = 1
value  bcd - num of occurrences = 1
value  c   - num of occurrences = 1
value  cd  - num of occurrences = 1
value  d   - num of occurrences = 1

您可以将
3
更改为置换字符串的最大长度。

打印“%10s”“%”mystring“怎么办"
在任何解决方案中都不作为选项列出。您也许应该提到负数给出左对齐的填充输出;这对初学者来说很难直观。@tripleee的+1表示@tripleee,如果没有您的负数给出左对齐的注释,我的脑袋会被敲得更长…thx m8。这比我不明白为什么Python中有这样的推向卷积,有一种方法在空白空间中填充一个特定的字符吗?例如,如果我们需要打印“05”而不是“5”。下面是一些使用f字符串进行优雅的固定宽度打印的技巧。此外,0表示format参数的位置,因此您可以做另外两件事:
{我无法再编辑上一条注释,这是需要的。
{这里是描述这些格式字符串和附加选项的Python。为了快速参考,
{0:that5中的空格可以是变量替换
>>>打印宽度20>>>打印“{0:您也可以使用数字,只需按
宽度=10;”的顺序列出变量{0:但这不会将字符串缩短到20个字符以上。请使用
'%(name)20.20s'
将20设置为最小和最大字符串长度!我最喜欢这个答案!
>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '
formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)
2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main
>>> print(f"{'123':<4}56789")
123 56789
__________________________________________________________________
Name                      Country                          Age
__________________________________________________________________
Niroshan                  Srilanka                          20
Brayan                    Australia                         25
Kate                      England                           30
__________________________________________________________________
print('123.00'.rjust(9))
print('123456.89'.rjust(9))

# expected output  
   123.00
123456.89
for prefix in unique:
    if prefix != "":
        print(f"value  {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")
value  a   - num of occurrences = 1
value  ab  - num of occurrences = 1
value  abc - num of occurrences = 1
value  b   - num of occurrences = 1
value  bc  - num of occurrences = 1
value  bcd - num of occurrences = 1
value  c   - num of occurrences = 1
value  cd  - num of occurrences = 1
value  d   - num of occurrences = 1