{"id":120741,"date":"2020-11-16T13:12:28","date_gmt":"2020-11-16T13:12:28","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=16851"},"modified":"2020-11-16T13:12:28","modified_gmt":"2020-11-16T13:12:28","slug":"python-int-to-string-with-leading-zeros","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/11\/16\/python-int-to-string-with-leading-zeros\/","title":{"rendered":"Python Int to String with Leading Zeros"},"content":{"rendered":"<p class=\"has-pale-cyan-blue-background-color has-background\">To convert an integer <code>i<\/code> to a string with leading zeros so that it consists of <code>5<\/code> characters, use the format string <code>f'{i:05d}'<\/code>. The <code>d<\/code> flag in this expression defines that the result is a decimal value. The <code>str(i).zfill(5)<\/code> accomplishes the same string conversion of an integer with leading zeros. <\/p>\n<p><strong>Challenge<\/strong>: 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. <\/p>\n<p><strong>Example<\/strong>: For integer 42, you want to fill it up with leading zeros to the following string with 5 characters: <code>'00042'<\/code>. <\/p>\n<p><em>In all methods, we assume that the integer has less than 5 characters. <\/em><\/p>\n<h2>Method 1: Format String<\/h2>\n<p>The first method uses the <a href=\"https:\/\/docs.python.org\/3\/library\/string.html#format-string-syntax\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/docs.python.org\/3\/library\/string.html#format-string-syntax\">format string feature<\/a> in Python 3+. They&#8217;re also called <em>replacement fields<\/em>. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Integer value to be converted\ni = 42 # Method 1: Format String\ns1 = f'{i:05d}'\nprint(s1)\n# 00042<\/pre>\n<p>The code <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">f'{i:05d}'<\/code> places the integer i into the newly created string. However, it tells the format language to fill the string to <code>5<\/code> characters with leading <code>'0'<\/code>s using the decimal system. This is the most Pythonic way to accomplish this challenge. <\/p>\n<h2>Method 2: zfill()<\/h2>\n<p>Another readable and Pythonic way to fill the string with leading 0s is the <code><a href=\"https:\/\/blog.finxter.com\/python-pad-zeros-to-a-string\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/blog.finxter.com\/python-pad-zeros-to-a-string\/\">string.zfill()<\/a><\/code> method. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Method 2: zfill()\ns2 = str(i).zfill(5)\nprint(s2)\n# 00042<\/pre>\n<p>The method takes one argument and that is the number of positions of the resulting string. Per default, it fills with 0s. <\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/11\/padString-1024x576.jpg\" alt=\"Python How to Pad Zeros to a String?\" class=\"wp-image-16905\" width=\"768\" height=\"432\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/11\/padString-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/11\/padString-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/11\/padString-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/11\/padString-150x84.jpg 150w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<\/div>\n<p>You can check out the following video tutorial from Finxter <strong>Adam<\/strong>:<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"Python How to Pad Zeros to a String Video\" width=\"1333\" height=\"1000\" src=\"https:\/\/www.youtube.com\/embed\/0F-qu-vkPYA?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<h2>Method 3: List Comprehension<\/h2>\n<p>Many Python coders don&#8217;t quite get the f-strings and the <code>zfill()<\/code> method shown in methods 2 and 3. If you don&#8217;t have time learning them, you can also use a more standard way based on <a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-concatenation\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Daily Python Puzzle: String Concatenation\">string concatenation<\/a> and <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">list comprehension<\/a>. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Method 3: List Comprehension\ns3 = str(i)\nn = len(s3)\ns3 = '0' * (5-len(s3)) + s3\nprint(s3)\n<\/pre>\n<p>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=5<\/code> characters and concatenate it to the integer&#8217;s string representation. The <a href=\"https:\/\/blog.finxter.com\/what-is-asterisk-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"What is the Asterisk \/ Star Operator (*) in Python?\">asterisk operator<\/a> creates a string of <code>5-len(s3)<\/code> zeros here. <\/p>\n<h2>Where to Go From Here?<\/h2>\n<p>Enough theory, let\u2019s get some practice!<\/p>\n<p>To become successful in coding, you need to get out there and solve real problems for real people. That\u2019s how you can become a six-figure earner easily. And that\u2019s how you polish the skills you really need in practice. After all, what\u2019s the use of learning theory that nobody ever needs?<\/p>\n<p><strong>Practice projects is how you sharpen your saw in coding!<\/strong><\/p>\n<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?<\/p>\n<p>Then become a Python freelance developer! It\u2019s the best way of approaching the task of improving your Python skills\u2014even if you are a complete beginner.<\/p>\n<p>Join my free webinar <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\">\u201cHow to Build Your High-Income Skill Python\u201d<\/a> and watch how I grew my coding business online and how you can, too\u2014from the comfort of your own home.<\/p>\n<p><a href=\"https:\/\/blog.finxter.com\/webinar-freelancer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Join the free webinar now!<\/a><\/p>\n<p>The post <a href=\"https:\/\/blog.finxter.com\/python-int-to-string-with-leading-zeros\/\" target=\"_blank\" rel=\"noopener noreferrer\">Python Int to String with Leading Zeros<\/a> first appeared on <a href=\"https:\/\/blog.finxter.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Finxter<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>To convert an integer i to a string with leading zeros so that it consists of 5 characters, use the format string f'{i:05d}&#8217;. The d flag in this expression defines that the result is a decimal value. The str(i).zfill(5) accomplishes the same string conversion of an integer with leading zeros. Challenge: Given an integer number. [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-120741","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/120741","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=120741"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/120741\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=120741"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=120741"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=120741"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}