>>print"{:>20}andstuff".format("test")testand" />
如何在python中使用特殊字符填充和对齐unicode字符串? 您所在的位置:网站首页 scum750ti 如何在python中使用特殊字符填充和对齐unicode字符串?

如何在python中使用特殊字符填充和对齐unicode字符串?

2023-03-26 19:51| 来源: 网络整理| 查看: 265

Python可以很容易地填充和对齐ascii字符串,如下所示:

>>> print "%20s and stuff" % ("test") test and stuff >>> print "{:>20} and stuff".format("test") test and stuff

但是,如何正确填充和对齐包含特殊字符的unicode字符串?我尝试了几种方法,但它们似乎都没有用:

#!/usr/bin/env python # -*- coding: utf-8 -*- def manual(data): for s in data: size = len(s) print ' ' * (20 - size) + s + " stuff" def with_format(data): for s in data: print " {:>20} stuff".format(s) def with_oldstyle(data): for s in data: print "%20s stuff" % (s) if __name__ == "__main__": data = ("xTest1x", "?Test?", "?? Test ??", "~Test2~") data_utf8 = map(lambda s: s.decode("utf8"), data) print "with_format" with_format(data) print "with_oldstyle" with_oldstyle(data) print "with_oldstyle utf8" with_oldstyle(data_utf8) print "manual:" manual(data) print "manual utf8:" manual(data_utf8)

这提供了不同的输出:

with_format xTest1x stuff ?Test? stuff ?? Test ?? stuff ~Test2~ stuff with_oldstyle xTest1x stuff ?Test? stuff ?? Test ?? stuff ~Test2~ stuff with_oldstyle utf8 xTest1x stuff ?Test? stuff ?? Test ?? stuff ~Test2~ stuff manual: xTest1x stuff ?Test? stuff ?? Test ?? stuff ~Test2~ stuff manual utf8: xTest1x stuff ?Test? stuff ?? Test ?? stuff ~Test2~ stuff

这是使用Python 2.7.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有