如何在 Python 3 中以字符串格式设置空格 [英] How to set the spaces in a string format in Python 3

查看:46
本文介绍了如何在 Python 3 中以字符串格式设置空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置字符串格式,以便可以使用变量来确保长度可以根据需要更改?例如,假设最初长度为 10,然后输入更改,然后长度变为 15.我将如何更新格式字符串?

 长度 = 0对于 self.rows 中的 i:对于 i 中的 j:如果 len(j) >长度:长度 = len(j)打印('%长度s')

显然上面的语法是错误的,但我不知道如何让它工作.

解决方案

Using str.format

<预><代码>>>>长度 = 20>>>string = "一些字符串">>>print('{1:>{0}}'.format(length, string))一些字符串

How can I set up the string format so that I could use a variable to ensure the length can change as needed? For example, lets say the length was 10 at first, then the input changes then length becomes 15. How would I get the format string to update?

    length =  0
    for i in self.rows:
        for j in i:
            if len(j) > length:
                length  = len(j)
    print('% length s')

Obviously the syntax above is wrong but I can't figure out how to get this to work.

解决方案

Using str.format

>>> length = 20
>>> string = "some string"
>>> print('{1:>{0}}'.format(length, string))
         some string

这篇关于如何在 Python 3 中以字符串格式设置空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆