【问题标题】:How to return a string of fixed length in python如何在python中返回一个固定长度的字符串
【发布时间】:2014-05-26 14:37:52
【问题描述】:

我有以下格式的字段:16,paul920140526,即count ++ name+ Id+ date+ space,共 12 个字符。

目前我正在通过执行以下操作返回它:

def formatField(self) :  
    self.Id = self.getNextId()  
    self.cnt = self.getCount()  
    return(self.cnt+','+self.Id+'            ')  

这里getNextId返回IdgetCount返回count(以字符串的形式)。但是,我意识到硬编码 12 个空格字符是一个坏主意,因为当id 从 9 增加到 10,即两位数时,空格应该从 12 个字符减少到 11 个字符。我应该如何确保整个 Field 保持固定长度?

提前致谢!

【问题讨论】:

标签: python string


【解决方案1】:

改变

return(self.cnt+','+self.Id+'            ')

s = str(self.cnt)+','+self.Id+'            '
return s[:13]

【讨论】:

    【解决方案2】:

    在最简单的情况下,如果您已经用空格填充,则可以使用 Python 数组切片来获得正确的长度。

    例如:

    myWidth=30 # For example, this depends on how 'wide' you want the string to be.
    myString = self.cnt+','+self.Id+'            '
    return mystring[:MyWidth]
    

    【讨论】:

      【解决方案3】:

      你可以试试ljust()函数

      https://docs.python.org/2/library/string.html

      【讨论】:

        【解决方案4】:

        所有其他选项都有效(我喜欢.ljust()),但为了完整起见,我将添加以下选项:

        def formatField(self, length=30):
            self.Id = self.getNextId()
            self.cnt = self.getCount()
        
            field = str(self.Id) + ',' + str(self.cnt)
            field += ' ' * max(0, length - len(field)
        
            return field
        

        【讨论】:

          猜你喜欢
          • 2017-05-12
          • 2011-01-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-14
          • 1970-01-01
          • 2016-04-01
          • 1970-01-01
          相关资源
          最近更新 更多