there is no inbuilt zfill but I use this zfl function
def zfl(s, width):
# Pads the provided string with leading 0's to suit the specified 'chrs' length
# Force # characters, fill with leading 0's
return '{:0>{w}}'.format(s, w=width)
This might be useful to you? Just pass the string and the string width you require.
Answer from user12757608 on Stack Overflowthere is no inbuilt zfill but I use this zfl function
def zfl(s, width):
# Pads the provided string with leading 0's to suit the specified 'chrs' length
# Force # characters, fill with leading 0's
return '{:0>{w}}'.format(s, w=width)
This might be useful to you? Just pass the string and the string width you require.
welcome to SO!
No, MicroPython does not have a zfill method on strings.
If you're looking for a specific width, you'll need to get a len(str) and then concatenate the desired string of "0"s to the start of string.
When you use
for i in t:
i is not index, each item.
>>> for i in t:
... print(i)
...
2019
10
11
3
40
8
686538
None
If you want to use index, do like following:
>>> for i, v in enumerate(t):
... print("{} is {}".format(i,v))
...
0 is 2019
1 is 10
2 is 11
3 is 3
4 is 40
5 is 8
6 is 686538
7 is None
another way to create '191011034008'
>>> t = (2019, 10, 11, 3, 40, 8, 686538, None)
>>> "".join(map(lambda x: "%02d" % x, t[:6]))
'20191011034008'
>>> "".join(map(lambda x: "%02d" % x, t[:6]))[2:]
'191011034008'
note that:
%02dadd leading zero when argument is lower than 10 otherwise (greater or equal 10) use itself. So year is still 4digit string.This lambda does not expect that argument is None.
I tested this code at https://micropython.org/unicorn/
edited :
str.format method version:
"".join(map(lambda x: "{:02d}".format(x), t[:6]))[2:]
or
"".join(map(lambda x: "{0:02d}".format(x), t[:6]))[2:]
second example's 0 is parameter index.
You can use parameter index if you want to specify it (ex: position mismatch between format-string and params, want to write same parameter multiple times...and so on) .
>>> print("arg 0: {0}, arg 2: {2}, arg 1: {1}, arg 0 again: {0}".format(1, 11, 111))
arg 0: 1, arg 2: 111, arg 1: 11, arg 0 again: 1
I'd recommend you to use Python's string formatting syntax.
>> t = (2019, 10, 11, 3, 40, 8, 686538, None)
>> r = ("%d%02d%02d%02d%02d%02d" % t[:-2])[2:]
>> print(r)
191011034008
Let's see what's going on here:
- %d means "display a number"
- %2d means "display a number, at least 2 digits"
- %02d means "display a number, at least 2 digits, pad with zeroes"
so we're feeding all the relevant numbers, padding them as needed, and cut the "20" out of "2019".
Let's say I input a as my variable. I want it to display 01100001
That's it. I've tried everything but for some reason micropython shits itself when I try to use conversion_binary = ''.join(format(ord(i), '08b') for i in lett)"
And yet normal Python works just fine. I don't get it. It just says that "format" isn't defined.