create account

Python String Formatting and Tricks By albro by albro

View this thread on: hive.blogpeakd.comecency.com
· @albro ·
$4.71
Python String Formatting and Tricks By albro
<center>![Python String Formatting and Tricks](https://files.peakd.com/file/peakd-hive/albro/EoAU2QSpU5Yex1SYGGWR1ag6wauJ9SeWFrV5W74yTPqqP2g42MwAyr2v2iD47amURYv.jpg)</center>

<p>In different projects, we need to combine variables and text strings. With the help of string formatting in Python, we can create a regular structure to print the variable between the text string. These constructs help make the code more readable and of course improve debugging and development. In this post, I'll talk about 3 ways to format Python text strings.</p>
<p>We have two variables named <code>name</code> and <code>power</code>; The first one specifies the person's name and the second one specifies his power. Suppose the name of the person is <code>albro</code> and his power is <code>90</code>, and we want to print a text similar to the following in the output:</p>
<pre><code>albro power is: 90</code></pre>
<p>We use the <code>print()</code> function to print texts in the console. The first method is to use the <a href="https://peakd.com/hive-169321/@albro/python-print-in-output-5-tricks-by-albro">print tricks in Python</a> to connect the variable and the string and print it in the output. As a result, we have a code similar to the following:</p>
<pre><code>name  = "albro"
power = 90
print( name + "'s power is:", power )</code></pre>
<p>If the number of variables increases or if we want to create a more complex text string, this method does not look very interesting! Therefore, we use string formatting methods.</p>
<h3>String formatting methods in Python</h3>
<p>In addition to the fact that using variables directly in the string isn't interesting, it can sometimes hurt the readability of the code and the development process! So always try to use the features of different languages to improve your programming skills.</p>
<p>There are three ways to format a string in Python:</p>
<ul>
<li>Using the <code>format()</code> method on the string</li>
<li>Using the <code>f</code> method and placing it before the string definition</li>
<li>Using the <code>%-formatting</code> method, which is a bit older.</li>
</ul>
<p><strong>Python string formatting with <code>format()</code></strong></p>
<p>The <code>str.format()</code> method in Python is used to organize long strings with many variables. Of course, this does not mean that it cannot be used for a short string of one variable.</p>
<p>This method is called on text string variables. <code>str</code> means string data type in Python. This method is used to prepare the string.</p>
<p>To use <code>format()</code>, we must determine the position of the variables in the string with <code>{}</code> (open and closed braces). Consider the same first example. In the final text string, we had two variables. So we change the string as follows:</p>
<pre><code>txt = "{}'s power is: {}"</code></pre>
<p>Now it is enough to call the format method on the structured string and give it the variables.</p>
<pre><code>txt = "{}'s power is: {}".format( name, power )</code></pre>
<p>Now, if we print the value of the <code>txt</code> variable in the output, we will have the following result:</p>
<pre><code>print(txt)
# albro's power is: 90</code></pre>
<p>What we did was the simplest way to use string formatting in Python. In this case, the position of the variables is counted from the leftmost position in the text and its equivalent should be determined as the input of the <code>format()</code> function.</p>
<p><strong>Determining the index of the variable in the format method</strong></p>
<p>In order to specify the index of each variable in the string, it's enough to specify the desired index inside the braces. The code below is exactly the same as the default formatted string structure without specifying the indices.</p>
<pre><code>txt = "{0}'s power is: {1}".format( name, power )</code></pre>
<p>In the following code, I moved the index of the variables and as you can see in the output, the order of calling and placing the variables in the string has been moved.</p>
<pre><code>txt = "{1}'s power is: {0}".format( name, power )
print(txt)
# 90's power is: albro</code></pre>
<p><strong>Names for variables within the string</strong></p>
<p>In addition to the index number, we can determine the position of the variables with the help of the desired names. Just like when formatting a text string with Python, we set a variable name for each position and set a value for those variables when calling the <code>format()</code> method.</p>
<p>In the following code, I have first defined a <a href="https://peakd.com/hive-169321/@albro/python-list-and-tricks-by-albro">Python list</a> called <code>data</code> to determine the values. We could use single variables, or other data structures, as before. Then I choose a name for each position and use them when calling <code>format()</code>.</p>
<pre><code>data = ["ocdb", 80]
txt = "{name}'s power is: {power}".format( name=data[0], power=data[1] )<br />
# ocdb's power is: 80</code></pre>
<p>Pay attention that when specifying the inputs of the string format function, we must specify the name of the desired location.</p>
<p><strong>Format strings with f-string</strong></p>
<p>This method is very similar to the previous method; That is, instead of variables in the text string, we use braces. This method was added from Python version 3.6.</p>
<p>To format the Python string with f, it is enough to put the letter f before the text string and put the main name of global variables directly inside <code>{}</code>. For a better understanding, consider the following example:</p>
<pre><code>name  = "ocdb"
power = 80
txt = f"{name}'s power is: {power}"<br />
print(txt)
# ocdb's power is: 80</code></pre>
<p>The letter we place before the beginning of the text string can be a lowercase (f) or an uppercase (F); The result will make no difference.</p>
<p>Suppose we have a list of three <a href="https://peakd.com/hive-169321/@albro/python-dictionary-and-tricks-by-albro">dictionaries in Python</a>. One person's name and power are written in each dictionary. With the help of a <a href="https://peakd.com/hive-169321/@albro/python-loops-and-tricks-by-albro"><code>for</code> loop</a>, we print the power of these three people in the output:</p>
<pre><code>powers = [{'name': 'ocdb' , 'power': 80},
          {'name': 'albro', 'power': 95},
		  {'name': 'ecency' , 'power': 90}]<br />
for hiver in powers:
    print( f"{hiver['name']}'s power is: {hiver['power']}" )<br />
# Result:
# ocdb's power is: 80
# albro's power is: 95
# ecency's power is: 90</code></pre>
<p><strong>Python string formatting with <code>%</code></strong></p>
<p>The third method can be considered the oldest method for formatting the text structure in Python. Of course, this does not mean that this method is outdated or ineffective. This type of formatting is used in many projects.</p>
<p>For this, we must first determine the location and type of variables within the text. This is done with the help of the percent sign (<code>%</code>) and a letter that indicates the type of variable value. After finishing the text string, we give the desired values to the string by putting <code>%</code>.</p>
<p>Notice the structure defined in the following code:</p>
<pre><code>name  = "albro"
power = 90
txt = "%s's power is: %d" % (name, power)<br />
print(txt)
# albro's power is: 90</code></pre>
<p>In this code, two positions <code>%s</code> and <code>%d</code> are determined in the string, and after the end of the string (after the sign <code>"</code>), we have given the values we want to format the text by inserting a <code>%</code>.</p>
<p>If we want to define only one variable in the string, we don't need to use tuple to refer its value and we can initialize it after putting <code>%</code>.</p>
<pre><code>name = "albro"
msg  = "Thanks for visiting %s hive blog!" % name<br />
print(msg)
# Thanks for visiting albro hive blog!</code></pre>
<p>To determine the variable type, we have three main types:</p>
<ul>
<li><code><strong>%s</strong></code>: String values</li>
<li><strong><code>%d</code></strong>: Integer values</li>
<li><strong><code>%f</code></strong>: Decimal values</li>
</ul>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 329 others
properties (23)
authoralbro
permlinkpython-string-formatting-and-tricks-by-albro
categoryhive-169321
json_metadata{"app":"peakd/2023.6.2","format":"markdown","author":"albro","tags":["development","programming","neoxiag","gosh","threads","chessbrothers","python","tricks","leofinance"],"users":["albro"],"image":["https://files.peakd.com/file/peakd-hive/albro/EoAU2QSpU5Yex1SYGGWR1ag6wauJ9SeWFrV5W74yTPqqP2g42MwAyr2v2iD47amURYv.jpg"]}
created2023-06-06 00:02:27
last_update2023-06-06 00:02:27
depth0
children6
last_payout2023-06-13 00:02:27
cashout_time1969-12-31 23:59:59
total_payout_value2.358 HBD
curator_payout_value2.355 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8,198
author_reputation30,477,419,385,789
root_title"Python String Formatting and Tricks By albro"
beneficiaries
0.
accounthive-169321
weight200
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,194,274
net_rshares12,084,450,866,407
author_curate_reward""
vote details (393)
@chessbrotherspro ·
<h3>Congratulations!</h3><hr /><div class="pull-right"><img src="https://images.hive.blog/DQmQLssYuuJP2neoTVUbMRzvAu4Ptg7Vwt92aTM7Z3gNovg/cb-logo-150.png" alt="You have obtained a vote from CHESS BROTHERS PROJECT"/></div><div class="text-justify"><h3>✅ Good job. Your post has been appreciated and has received support from <a href="/@chessbrotherspro"><b>CHESS BROTHERS</b></a> ♔ 💪</h3><p><br>♟ We invite you to use our hashtag <b>#chessbrothers</b> and learn more <a href="/@chessbrotherspro/introducing-chess-brothers-project-the-most-innovative-community-combining-chess-fitness-and-more"><b>about us</b></a>.</p><p>♟♟ You can also reach us on our <a href="https://discord.gg/73sK9ZTGqJ" rel="noopener" title="This is going to take you to the Discord of Chess Brothers"><b>Discord server</b></a>  and promote your posts there.</p><p>♟♟♟  Consider <a href="/@chessbrotherspro/teamwork-is-worthwhile-join-the-chess-brothers-healing-trail-supporting-the-work-being-done-and-earning-rewards"><b>joining our curation trail</b></a> so we work as a team and you get rewards automatically.</p><p>♞♟ Check out our <a href="/@chessbrotherspro"><b>@chessbrotherspro</b></a> account to learn about the curation process carried out daily by our team.</p><p><br>🏅 If you want to earn profits with your HP delegation and support our project, we invite you to join the <i>Master Investor</i> plan. <a href='/@chessbrotherspro/master-investor-plan-or-programa'>Here you can learn how to do it.</a></p></div><div class="text-center"><p><br>Kindly</p><p><strong><em>The CHESS BROTHERS team</em></strong></p></div>
properties (22)
authorchessbrotherspro
permlinkre-python-string-formatting-and-tricks-by-albro
categoryhive-169321
json_metadata""
created2023-06-06 14:23:15
last_update2023-06-06 14:23:15
depth1
children0
last_payout2023-06-13 14:23:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,598
author_reputation78,492,844,132,988
root_title"Python String Formatting and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,208,667
net_rshares0
@ecency ·
**Yay!** 🤗<br>Your content has been **boosted with Ecency Points**, by @albro. <br>Use Ecency daily to boost your growth on platform! <br><br><b>Support Ecency</b><br>[Vote for new Proposal](https://hivesigner.com/sign/update-proposal-votes?proposal_ids=%5B245%5D&approve=true)<br>[Delegate HP and earn more](https://ecency.com/hive-125125/@ecency/daily-100-curation-rewards)
properties (22)
authorecency
permlinkre-202366t65222339z
categoryhive-169321
json_metadata{"tags":["ecency"],"app":"ecency/3.0.20-welcome","format":"markdown+html"}
created2023-06-06 06:52:24
last_update2023-06-06 06:52:24
depth1
children0
last_payout2023-06-13 06:52:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length375
author_reputation628,525,970,064,641
root_title"Python String Formatting and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,201,382
net_rshares0
@hivebuzz ·
Congratulations @albro! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@albro/upvoted.png?202306060110"></td><td>You received more than 8000 upvotes.<br>Your next target is to reach 9000 upvotes.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@albro) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



**Check out our last posts:**
<table><tr><td><a href="/hive-122221/@hivebuzz/pum-202305-delegations"><img src="https://images.hive.blog/64x128/https://i.imgur.com/fg8QnBc.png"></a></td><td><a href="/hive-122221/@hivebuzz/pum-202305-delegations">Our Hive Power Delegations to the May PUM Winners</a></td></tr><tr><td><a href="/hive-122221/@hivebuzz/pud-202306-feedback"><img src="https://images.hive.blog/64x128/https://i.imgur.com/zHjYI1k.jpg"></a></td><td><a href="/hive-122221/@hivebuzz/pud-202306-feedback">Feedback from the June Hive Power Up Day</a></td></tr><tr><td><a href="/hive-122221/@hivebuzz/pum-202305-result"><img src="https://images.hive.blog/64x128/https://i.imgur.com/mzwqdSL.png"></a></td><td><a href="/hive-122221/@hivebuzz/pum-202305-result">Hive Power Up Month Challenge - May 2023 Winners List</a></td></tr></table>
properties (22)
authorhivebuzz
permlinknotify-albro-20230606t013324
categoryhive-169321
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2023-06-06 01:33:24
last_update2023-06-06 01:33:24
depth1
children0
last_payout2023-06-13 01:33:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,457
author_reputation370,483,530,124,856
root_title"Python String Formatting and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,195,681
net_rshares0
@mikezillo ·
As a Guest curator for Ecency, I think that you provided value with such explanations.
properties (22)
authormikezillo
permlinkre-albro-202366t85317656z
categoryhive-169321
json_metadata{"tags":["development","programming","neoxiag","gosh","threads","chessbrothers","python","tricks","leofinance"],"app":"ecency/3.0.32-vision","format":"markdown+html"}
created2023-06-06 06:53:18
last_update2023-06-06 06:53:18
depth1
children0
last_payout2023-06-13 06:53:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length86
author_reputation181,498,315,026,789
root_title"Python String Formatting and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,201,414
net_rshares0
@poshthreads ·
$0.02
https://leofinance.io/threads/albro/re-leothreads-2sml4cum5
<sub> The rewards earned on this comment will go directly to the people ( albro ) sharing the post on LeoThreads,LikeTu,dBuzz.</sub>
👍  ,
properties (23)
authorposhthreads
permlinkre-albro-python-string-formatting-and-tricks-by-albro-2118
categoryhive-169321
json_metadata"{"app":"Poshtoken 0.0.2","payoutToUser":["albro"]}"
created2023-06-06 00:22:12
last_update2023-06-06 00:22:12
depth1
children0
last_payout2023-06-13 00:22:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.019 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length193
author_reputation415,471,585,053,248
root_title"Python String Formatting and Tricks By albro"
beneficiaries
0.
accountnomnomnomnom
weight10,000
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id124,194,591
net_rshares97,733,232,035
author_curate_reward""
vote details (2)
@stemsocial ·
re-albro-python-string-formatting-and-tricks-by-albro-20230607t155404393z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.&nbsp;<br />&nbsp;<br />
</div>
properties (22)
authorstemsocial
permlinkre-albro-python-string-formatting-and-tricks-by-albro-20230607t155404393z
categoryhive-169321
json_metadata{"app":"STEMsocial"}
created2023-06-07 15:54:03
last_update2023-06-07 15:54:03
depth1
children0
last_payout2023-06-14 15:54:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length565
author_reputation22,927,823,584,327
root_title"Python String Formatting and Tricks By albro"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id124,240,281
net_rshares0