Pad a String representation of a multi-digit number
I want to convert any integer into a two-or-more digit number, such that 0 becomes “00”, 9 becomes “09”, but 10 becomes “10”.
However, I do not want to use dynamic typing.
A clumsy way of achieving this is to reassign a scoped variable from integer to string:
def convert_to_two_digit_string(num):
# Convert integer to string
num_str = str(num)
# If the length of the string is less than 2, pad it with leading zeros
if len(num_str) < 2:
num_str = '0' + num_str
return num_str
But a better way I think is this:
num_str = "{:02d}".format(num)
Or this:
num_str = f"{num:02d}"
Published on 22 Apr 2024
all tags
100daysofcode activerecord android annoyances api apt arch array artix atom az3w backend bash blog browser bug callback career ci-cd cli cloud code coding config configuration cp crud cryptography css csv database db design devops django docker email erp feelsgood filter fugitive gif gist git gnome gnome pomodoro grep hebrew http ide isbn-fetcher iso javascript job search js kanban kindle koans learning linkedin linux logger manjaro map markdown microservices mobi mtp neovim nodejs nvchad packages panda pastbin patch portfolio post postgres pytest python rails reduce refactoring reflections rest routes rspec ruby salesforce script scripting security sed shell sql string_replacement study tdd terminal testing tmux ttd version_control vim vim sort walkthrough webdev workflow zsh