【问题标题】:python if a list is over 20 characters shorten it to 20 if it is less than 20 characters, add 0s to make it 20 [closed]python 如果列表超过 20 个字符,则将其缩短为 20 如果它少于 20 个字符,则添加 0 使其变为 20 [关闭]
【发布时间】:2014-02-08 15:08:36
【问题描述】:

在 python 程序中,我有

...
wf = raw_input("enter string \n")
wl = list(wf)
wd = wl[:-4] 
#now I want to see if wl is over 20 characters
#if it is, I want it truncated to 20 characters
#if not, I want character appended until it is 20 characters
#if it is 20 characters leave it alone
...

请帮助评论的东西按照它所说的去做

【问题讨论】:

  • 这个问题似乎离题了,因为它是关于为你编写代码的。
  • @MaximeLorant 我无法确定要调用的特定函数以便可以附加 0。我尝试了一些不同的方法,但它们不起作用。没听说过str的zfill属性,也没听说过rjust/ljust。在我拥有的有关 Python 的书中没有提到它们。

标签: python list python-3.x truncate


【解决方案1】:

最简单的方法是使用切片和str.zfill函数,像这样

data = "abcd"
print data[:20].zfill(20)       # 0000000000000000abcd

当data为abcdefghijklmnopqrstuvwxyz时,输出为

abcdefghijklmnopqrst

注意:如果你的意思是,附加零,你可以使用str.ljust函数,像这样

data = "abcdefghijklmnopqrstuvwxyz"
print data[:20].ljust(20, "0")        # abcdefghijklmnopqrst

data = "abcd"
print data[:20].ljust(20, "0")        # abcd0000000000000000

使用ljust和rjust的好处是,我们可以使用任意填充字符。

【讨论】:

  • 非常有趣。有没有填充前缀的函数?
  • @GrijeshChauhan 您可以使用ljust 和rjust。检查这些链接。 :)
  • 感谢您的链接:)
  • @GrijeshChauhan 不客气 :)
【解决方案2】:

使用str.format:

>>> '{:0<20.20}'.format('abcd') # left align
'abcd0000000000000000'
>>> '{:0>20.20}'.format('abcd') # right align
'0000000000000000abcd'
>>> '{:0<20.20}'.format('abcdefghijklmnopqrstuvwxyz')
'abcdefghijklmnopqrst'

或format:

>>> format('abcd', '0<20.20')
'abcd0000000000000000'
>>> format('abcdefghijklmnopqrstuvwxyz', '0<20.20')
'abcdefghijklmnopqrst'

关于使用的格式规范:

0: fill character.
<, >: left, right align.
20: width
.20: precision (for string, limit length)

【讨论】:

  • 我试图理解你的伎俩但我不能。你能解释一下格式字符串0&lt;20.20
  • @GrijeshChauhan,在我的回答中,给出了关于规范 0&lt;20.20 的解释。请告诉我哪个部分很难获得。
  • @falsetrue 是的,我再次阅读,在我的系统上尝试过。现在完全明白了谢谢!..真的很有趣。
【解决方案3】:

一个简单的可以是(读cmets):

def what(s):
    l = len(s)
    if l == 20:  # if length is 20  
     return s    # return as it is
    if l > 20:   # > 20
     return s[:20] # return first 20
    else:
     return s + '0' * (20 - l) # add(+)  (20 - length)'0's

print what('bye' * 3)
print what('bye' * 10)
print what('a' * 20)

输出:

$ python x.py
byebyebye00000000000
byebyebyebyebyebyeby
aaaaaaaaaaaaaaaaaaaa

【讨论】:

    【解决方案4】:

    如果您想将其作为列表使用,如上所述,那么list comprehension 将带您到达那里:

    my_data = 'abcdef'
    
    my_list = list(my_data)
    my_list = [my_list[i] if i < len(my_list) else 0 for i in range(20)]
    
    print my_list
    

    输出:

    ['a', 'b', 'c', 'd', 'e', 'f', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    

    这也包括 >= 20 个字符的情况。

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      相关资源
      最近更新 更多