Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Int to String with Leading Zeros

#1
Python Int to String with Leading Zeros

<div><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>
<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>
<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>
<p><em>In all methods, we assume that the integer has less than 5 characters. </em></p>
<h2>Method 1: Format String</h2>
<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’re also called <em>replacement fields</em>. </p>
<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
i = 42 # Method 1: Format String
s1 = f'{i:05d}'
print(s1)
# 00042</pre>
<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>
<h2>Method 2: zfill()</h2>
<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>
<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()
s2 = str(i).zfill(5)
print(s2)
# 00042</pre>
<p>The method takes one argument and that is the number of positions of the resulting string. Per default, it fills with 0s. </p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img 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/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<p>You can check out the following video tutorial from Finxter <strong>Adam</strong>:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe 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>
</div>
</figure>
<h2>Method 3: List Comprehension</h2>
<p>Many Python coders don’t quite get the f-strings and the <code>zfill()</code> method shown in methods 2 and 3. If you don’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 — A Helpful Illustrated Guide">list comprehension</a>. </p>
<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
s3 = str(i)
n = len(s3)
s3 = '0' * (5-len(s3)) + s3
print(s3)
</pre>
<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’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>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>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?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<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>
<p>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.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<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>
</div>


https://www.sickgaming.net/blog/2020/11/...ing-zeros/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016