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.
How to pad a numeric string with zeros to the right in Python? - Stack Overflow
Add leading zeros based on condition in python - Stack Overflow
Equivalent of Python zfill? - Ruby - Ruby-Forum
string - add leading zeros to a list of numbers in 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'
Let us do np.where combine with zfill, alternative you can check with str.pad
df.Random=np.where(df.Random.str.len()<9,df.Random.str.zfill(9),df.Random.str.zfill(20))
df
Out[9]:
Random
0 000000086
1 00000000007639103627
2 000000096
3 000000032
4 00000000001469476501
I used 'apply' combined with the fill_zeros function written below to get a run time of 603ms over a dataframe of 1,000,000 rows.
data = {
'Random': [str(randint(0, 100_000_000)) for i in range(0, 1_000_000)]
}
df = pd.DataFrame(data)
def fill_zeros(x):
if len(x) < 9:
return x.zfill(9)
else:
return x.zfill(20)
%timeit df['Random'].apply(fill_zeros)
603 ms ± 1.23 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Compared to:
%timeit np.where(df.Random.str.len()<9,df.Random.str.zfill(9),df.Random.str.zfill(20))
1.57 s ± 6.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
I’m trying to learn all of Python’s built-in functions before starting OOP, so I’m curious how this function could be used in real projects.