![]() |
|
[Tut] Python Int to String with Leading Zeros - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Int to String with Leading Zeros (/thread-98304.html) |
[Tut] Python Int to String with Leading Zeros - xSicKxBot - 11-17-2020 Python Int to String with Leading Zeros To convert an integer Code: iCode: 5Code: f'{i:05d}'Code: dCode: str(i).zfill(5)Challenge: Given an integer number. How to convert it to a string by adding leading zeros so that the string has a fixed number of positions. Example: For integer 42, you want to fill it up with leading zeros to the following string with 5 characters: Code: '00042'In all methods, we assume that the integer has less than 5 characters. Method 1: Format String The first method uses the format string feature in Python 3+. They’re also called replacement fields. Code: # Integer value to be converted
i = 42 # Method 1: Format String
s1 = f'{i:05d}'
print(s1)
# 00042The code Code: f'{i:05d}'Code: 5Code: '0'Method 2: zfill() Another readable and Pythonic way to fill the string with leading 0s is the Code: string.zfill()Code: # Method 2: zfill()
s2 = str(i).zfill(5)
print(s2)
# 00042The method takes one argument and that is the number of positions of the resulting string. Per default, it fills with 0s. ![]() You can check out the following video tutorial from Finxter Adam: Method 3: List Comprehension Many Python coders don’t quite get the f-strings and the Code: zfill()Code: # Method 3: List Comprehension
s3 = str(i)
n = len(s3)
s3 = '0' * (5-len(s3)) + s3
print(s3)You first convert the integer to a basic string. Then, you create the prefix of 0s you need to fill it up to Code: n=5Code: 5-len(s3)Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! The post Python Int to String with Leading Zeros first appeared on Finxter. |