Remove leading '0's from all strings in a list - python

My code
l=['99','08','096']
for i in l:
if i.startswith('0'):
i.replace('0','')
print(l)
Output
l=['99','08','096']
I just want to remove the leading '0's from all the strings:
l=['99','8','96']

You can use str.lstrip() for this in a list comprehension - to remove all leading '0's from each string.
>>> l = ['99', '08', '096']
>>> [x.lstrip('0') for x in l]
['99', '8', '96']
This has the added benefit of not removing instances of '0' from within the string, only from the front.
>>> l=['99', '08', '096', '0102']
>>> [x.lstrip('0') for x in l]
['99', '8', '96', '102']

If I understood you correctly, you want to remove the string from the array if it starts with 0, but from the code you showed, you are just replacing the 0 in the string with nothing. i.replace('0','')
one way to filter out is:
new_list = [el for el in l if not el.startswith('0')]

you can use list comprehension to correct your strings by using str.lstrip:
[e.lstrip('0') for e in l]
or you can use a for loop:
for i in range(len(l)):
if l[i].startswith('0'):
l[i] = l[i][1:]

Related

How to add digit in the beginning of string array in python?

e.g. I have this array
list=['123', '4', '56']
I want to add '0' in the beginning of list array that has 1 or 2 digit. So the output will be:
list=['123', '004', '056']
Use zfill method:
In [1]: '1'.zfill(3)
Out[1]: '001'
In [2]: '12'.zfill(3)
Out[2]: '012'
Using a list comprehension, we can prepend the string '00' to each number in the list, then retain the final 3 characters only:
list = ['123', '4', '56']
output = [('00' + x)[-3:] for x in list]
print(output) # ['123', '004', '056']
As per How to pad zeroes to a string?, you should use str.zfill:
mylist = ['123', '4', '56']
output = [x.zfill(3) for x in mylist]
Alternatively, you could (though I don't know why you would) use str.rjust
output = [x.rjust(3, "0") for x in mylist]
or string formatting:
output = [f"{x:0>3}" for x in mylist]
I'd say this would be a very easy to read example, but not the shortest.
Basically, we iterate through the lists elements, check if the length is 2 or 1. Based on that we will add the correct amount of '0'
lst=['123', '4', '56']
new = []
for numString in lst:
if len(numString) == 2:
new.append('0'*1+numString)
elif len(numString) == 1:
new.append('0'*2+numString)
else:
new.append(numString)
print(new)
Also I kind of had to include it (list comprehension).But this is barely readable,so I gave the above example. Look here for list comprehension with if, elif, else
lst=['123', '4', '56']
new = ['0'*1+numString if len(numString) == 2 else '0'*2+numString if len(numString) == 1 else numString for numString in lst]
print(new)
output
['123', '004', '056']
trying into integer and add preceding zero/s then convert into a string and replace the element in the same position and the same list
list=["3","45","111"]
n=len(list)
for i in range(0,n):
list[i] = str(f"{int(list[i]):03}")
You can check the solution for this in link

How to remove preceding zeros in a string element from a Python list

I have a list:
my_list = ['0300', '0023', '0005', '000030']
I want to remove the preceding zeroes in each string element from the list. So I want strip the 0s from the left side of the string.
Output would be like this:
my_list = ['300', '23', '5', '30']
I've tried this:
for x in my_list:
x = re.sub(r'^0+', "", x)
print my_list
But it doesn't seem to work. Please help!
You can use str.lstrip like this
print [item.lstrip('0') for item in l]
# ['300', '23', '5', '30']
Try:
list = [str(int(el)) for el in list]
Edit: pick the other answer, I'd prefer that one too :-)

How to remove specific strings from a list

From the following list how can I remove elements ending with Text.
My expected result is a=['1,2,3,4']
My List is a=['1,2,3,4,5Text,6Text']
Should i use endswith to go about this problem?
Split on commas, then filter on strings that are only digits:
a = [','.join(v for v in a[0].split(',') if v.isdigit())]
Demo:
>>> a=['1,2,3,4,5Text,6Text']
>>> [','.join(v for v in a[0].split(',') if v.isdigit())]
['1,2,3,4']
It looks as if you really wanted to work with lists of more than one element though, at which point you could just filter:
a = ['1', '2', '3', '4', '5Text', '6Text']
a = filter(str.isdigit, a)
or, using a list comprehension (more suitable for Python 3 too):
a = ['1', '2', '3', '4', '5Text', '6Text']
a = [v for v in a if v.isdigit()]
Use str.endswith to filter out such items:
>>> a = ['1,2,3,4,5Text,6Text']
>>> [','.join(x for x in a[0].split(',') if not x.endswith('Text'))]
['1,2,3,4']
Here str.split splits the string at ',' and returns a list:
>>> a[0].split(',')
['1', '2', '3', '4', '5Text', '6Text']
Now filter out items from this list and then join them back using str.join.
try this. This works with every text you have in the end.
a=['1,2,3,4,5Text,6Text']
a = a[0].split(',')
li = []
for v in a:
try : li.append(int(v))
except : pass
print li

How can I split a list into smaller lists?

I have a list:
lists = (['1','2','3','S','3','4','S','4','6','7'])
And I want to split the list into s smaller list everytime 'S' appears and eliminate 'S' into something like:
([['1','2','3'],['3','4],['4','6','7']])
My code:
def x (lists):
empty = ''
list = []
for x in lists:
if x == empty:
list[-1:].append(x)
else:
list.append([x])
return (list)
I tried something like this, but I am quite new to python, and Im getting nowhere. Nothing fancy please, how would I fix what I have?
Try itertools.groupby():
>>> from itertools import groupby
>>> lists = ['1','2','3','S','3','4','S','4','6','7']
>>> [list(g[1]) for g in groupby(lists, lambda i:i!='S') if g[0]]
[['1', '2', '3'], ['3', '4'], ['4', '6', '7']]
Maybe something like map(list,''.join(lists).split('S'))
Alternately, [list(s) for s in ''.join(lists).split('S'))
Well, may be funny, but this should work:
[s.split('#') for s in '#'.join(lists).split('#S#')]
Instead of the '#' any character can be used if it's unlikely to appear in lists.

How do I remove hyphens from a nested list?

In the nested list:
x = [['0', '-', '3', '2'], ['-', '0', '-', '1', '3']]
how do I remove the hyphens?
x = x.replace("-", "")
gives me AttributeError: 'list' object has no attribute 'replace', and
print x.remove("-")
gives me ValueError: list.remove(x): x not in list.
x is a list of lists. replace() will substitute a pattern string for another within a string. What you want is to remove an item from a list. remove() will remove the first occurrence of an item. A simple approach:
for l in x:
while ("-" in l):
l.remove("-")
For more advanced solutions, see the following: Remove all occurrences of a value from a Python list

Categories

Resources