Home > Blockchain >  How to remove select characters from a list of strings, and make a list of strings exactly 4 charact
How to remove select characters from a list of strings, and make a list of strings exactly 4 charact

Time:03-06

d = ['10303', '423078', '603', '502090']

Hey can someone show me how I would go through this list and do 2 separate things in 2 separate steps, also I don't want to create a function.

  1. I want to go through the list and remove '0' from all of the strings so make 10303-->133

  2. make the length of each of the strings exactly 4, so if the length of a string is greater than 0 make it exactly 4 by slicing it shorter eg. 24567-->2456, or it was shorter than 0 make it exactly 4 by adding 0 to the end eg. 133-->1330

CodePudding user response:

We can do this as follows:

d = ['10303', '423078', '603', '502090']

for i in d:
  j = (i.replace('0','') '0000')[0:4]
  print(j)
~/tests/py $ python stringLoop

Which prints out

1330
4237
6300
5290

replace removes the 0's
we add 4 0's and keep the first 4 characters

CodePudding user response:

    d = ['10303', '423078', '603', '502090']

for i in range(len(d)):
    d[i] = d[i].replace('0','')


for i in range(len(d)):
    print(d[i])
    if len(d[i]) > 3:
        d[i] = d[i][:4]
    else:
        d[i] = d[i].ljust(4, '0')

CodePudding user response:

Check the below code would work for you.

d = ['10303', '423078', '603', '502090']

# We are replacing the 0 values and simultaneously padding the values 0 towards right such that the max length is just 4
d = [x.replace('0','').ljust(4,'0') for x in d]
print(d)

# Output
['1330', '42378', '6300', '5290']
  • Related