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

2024-12-31 08:37:00
admin
原创
192
摘要:问题描述:我有以下代码(打印字符串中所有排列的出现):def splitter(str): for i in range(1, len(str)): start = str[0:i] end = str[i:] yield (start, end) ...

问题描述:

我有以下代码(打印字符串中所有排列的出现):

def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result    

el =[]

string = "abcd"
for b in splitter(string):
    el.extend(b)

unique = sorted(set(el))

for prefix in unique:
    if prefix != "":
        print "value  " , prefix  , "- 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

如何使用format或 f 字符串使输出排列成直列?


解决方案 1:

我发现使用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'

如果您想要将字符串与右侧对齐,>请使用<

>>> '{0: >5}'.format('ss')
'   ss'

编辑 1:正如评论中提到的:0in'{0: <5}'表示传递给的参数的索引str.format()


编辑2:在python3中也可以使用f字符串:

sub_str='s'
for i in range(1,6):
    s = sub_str*i
    print(f'{s:>5}')
    
'    s'
'   ss'
'  sss'
' ssss'
'sssss'

或者:

for i in range(1,5):
    s = sub_str*i
    print(f'{s:<5}')
's    '
'ss   '
'sss  '
'ssss '
'sssss'

值得注意的是,在上面一些地方,' '添加了(单引号)来强调打印字符串的宽度。

解决方案 2:

编辑 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

附注:我只是想知道您是否知道itertools模块的存在。例如,您可以使用以下代码在一行中获取所有组合的列表:

>>> [''.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']

combinations并且您可以通过与 结合使用来获取出现的次数count()

解决方案 3:

最初发布为对@0x90 答案的编辑,但由于偏离帖子的初衷而被拒绝,并建议作为评论或答案发布,因此我在这里附上简短的文字说明。

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

width=10
'{0: <{width}}'.format('sss', width=width)

此外,您可以通过仅使用数字并依赖于传递给的参数的顺序来使该表达式更简洁format

width=10
'{0: <{1}}'.format('sss', width)

或者甚至省略所有数字,以实现最大的、可能非 Python 隐式的紧凑性:

width=10
'{: <{}}'.format('sss', width)

更新 2017-05-26

随着Python 3.6 中格式化字符串文字(简称“f 字符串”)的引入,现在可以使用更简洁的语法访问以前定义的变量:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

这也适用于字符串格式

>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '

解决方案 4:

format绝对是最优雅的方式,但据我所知你不能将它与 python 的logging模块一起使用,因此你可以使用以下格式来实现%

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

更多信息请参阅此处的文档:https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

解决方案 5:

当您想在一个打印语句中打印多个元素时,这将有助于保持固定的长度。

25s格式化一个包含 25 个空格的字符串,默认左对齐。

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

members=["Niroshan","Brayan","Kate"]
print("__________________________________________________________________")
print('{:25s} {:32s} {:35s} '.format("Name","Country","Age"))
print("__________________________________________________________________")
print('{:25s} {:30s} {:5d} '.format(members[0],"Srilanka",20))
print('{:25s} {:30s} {:5d} '.format(members[1],"Australia",25))
print('{:25s} {:30s} {:5d} '.format(members[2],"England",30))
print("__________________________________________________________________")

这将打印

__________________________________________________________________
Name                      Country                          Age
__________________________________________________________________
Niroshan                  Srilanka                          20
Brayan                    Australia                         25
Kate                      England                           30
__________________________________________________________________

解决方案 6:

>>> print(f"{'123':<4}56789")
123 56789

解决方案 7:

我发现ljust()rjust()固定宽度打印字符串或用空格填充 Python 字符串非常有用。

一个例子

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为排列字符串的最大长度。

解决方案 8:

使用 f 字符串与使用格式一样有效:

https://scientificallysound.org/2016/10/17/python-print3/

f'{some_varaible:<20s}{some_varaible:_<20s}{some_varaible:.<20s}'

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2500  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1541  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   16  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   23  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   26  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用