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
Related
In a list of lists:
list=[['3','4','5'],['6','3','5'],['hello','goodbye','something56']]
I want to get rid of the one that has letters. My attempt is:
for i in sub_list:
if '.*[a-z]+.*' in i:
continue
else:
print(i)
However, this is not working.
Try to use str.isalpha() to check if string contains alphabet
list_of_lists = [['3','4','5'], ['6','3','5'], ['hello','goodbye','something56']]
for sub_list in list_of_lists:
if any(x.isalpha() for x in sub_list):
continue #this is what you are looking for
else:
print(sub_list)
Output
['3', '4', '5']
['6', '3', '5']
Using just basic Python (no libraries)
It's Bad form to name a variable list since it hides the built-in function list.
Code
numbers = "0123456789" # list of digits
lst = [['3','4','5'],['6','3','5'],['hello','goodbye','something56'], ['2', '4', 'today']]
new_lst = []
for sublist in lst:
new_sublist = []
for item in sublist:
for c in item:
if not c in numbers:
break
else:
# no break encountered so only numbers in for c in item
continue
break # break in for c initem, so issue break in for item in sublist
else:
# no break, so all items where numbers
new_lst.append(sublist) # sublist only had numbers
print(new_lst)
# Output: [['3', '4', '5'], ['6', '3', '5']]
I have my list:
l = [["1","2","3",["4","a"],"5"], ["6",["7"],"8","9"]]
I want it to become:
l = ["1","2","3","4-a","5","6","7","8","9"]
To finally transform it to a string separated by ";"
my_string: 1;2;3;4-a;5;6;7;8;9
I tried using the flat_list function but it's not doing what I want because it separates the "4" and "a" not how I want it:
def flat(sequence):
result = []
if isinstance(sequence, list):
for item in sequence:
if isinstance(item, list):
result += flat(item)
else:
result.append(item)
return result
else:
return sequence
It makes this:
l = [["1","2","3","4","a","5"],["6","7","8","9"]]
(By the way, if you have a better option of transforming the list into the string I want, feel free to explain it to me, I would be pleased of any solution)
If there is no more requirement, you could do some easy list comprehension:
l = [["1","2","3",["4","a"],"5"], ["6",["7"],"8","9"]]
resultList = ["-".join(j) if type(j) == list else j for i in l for j in i]
# ['1', '2', '3', '4-a', '5', '6', '7', '8', '9']
print(";".join(resultList))
# 1;2;3;4-a;5;6;7;8;9
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:]
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 :-)
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