Yes, there are the string justification methods, ljust and rjust.
>>> '12'.rjust(5, '#')
'###12'
>>> 'txt'.rjust(5, ' ')
' txt'
>>> '12'.ljust(5, '#')
'12###'
Answer from PM 2Ring on Stack OverflowYes, there are the string justification methods, ljust and rjust.
>>> '12'.rjust(5, '#')
'###12'
>>> 'txt'.rjust(5, ' ')
' txt'
>>> '12'.ljust(5, '#')
'12###'
If all you need is simple padding, I'd go with @PM2Ring's answer, but there is another, more versatile way, using the str.format method (Python 2.6 onward). This method allows you to interpolate the format specifier by nesting the replacement fields:
'{string:{fill}>{num}}'.format(string=string, fill=fill, num=num)
Replace > with < if you need to left-align the string instead.
Arcade equivalent of Python ".zfill" - Geographic Information Systems Stack Exchange
Equivalent of Python zfill? - Ruby - Ruby-Forum
How to pad a numeric string with zeros to the right in Python? - Stack Overflow
micropython - Is there a Zfill type function in micro python. Zfill in micro python - Stack Overflow
As maybe a alternative more portable [1] and efficient [2], actually you can just use str.ljust.
In [2]: '190'.ljust(8, '0')
Out[2]: '19000000'
In [3]: str.ljust?
Docstring:
S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
Type: method_descriptor
[1] format is not present on old python versions. format specifier was added since Python 3.0 (see PEP 3101) and Python 2.6.
[2] reverse twice is an expensive operation.
See Format Specification Mini-Language:
In [1]: '{:<08d}'.format(190)
Out[1]: '19000000'
In [2]: '{:>08d}'.format(190)
Out[2]: '00000190'
This also works with the Formatted String Literals, or f-strings for short (New in version 3.6):
In [1]: f'{190:<08d}'
Out[1]: '19000000'
In [2]: f'{190:>08d}'
Out[2]: '00000190'
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.
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.