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]

StackOverflow https://stackoverflow.com/questions/21647627

Domanda

in a python program, I have

...
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
...

please help with having the stuff commented do what it says

È stato utile?

Soluzione

The simplest way is to use slicing and str.zfill function, like this

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

When data is abcdefghijklmnopqrstuvwxyz, the output is

abcdefghijklmnopqrst

Note: If you really meant, appending zeros, you can use str.ljust function, like this

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

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

The advantage of using ljust and rjust is that, we can use arbitrary fill character.

Altri suggerimenti

Use str.format:

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

or format:

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

About format specification used:

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

One simple can be (read comments):

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)

output:

$ python x.py
byebyebye00000000000
byebyebyebyebyebyeby
aaaaaaaaaaaaaaaaaaaa

If you want to work with it as a list, as stated, then list comprehension will get you there:

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

output:

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

This also covers the >= 20 characters cases as well.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top