Formatting strings in Python is like drinking water while your body is upside-down for some of us. Well, I am here to make the drinking much easier by rotating you, but you have your own hands to drink, so I will have a task for you.
What is string formatting?
In any programming language, in this case, Python, we have different data types, i.e., string and integer. When representing these data types, we need to represent them in a way that will be understandable to the user who will be viewing the data. Let me show you a code example of what I mean.
Here I am simulating a situation where you would get the data of a user from the database and you want to represent the data to the user.The code above will print Awonke awonke@contawo 123 123.89842374, which is okay for us programmers, but you wouldn’t want to display it to the user like this, do you? (Please say no.)Therefore, we need to come up with ways to format this data for the user.
5 Ways to format strings
1.
Comma separation
2.
Concatenation
3.
Internal formatting
4.
External formatting
5.
Percentage formattingPlease note:
I have created some of these names from my big head. I thought I should let you know just in case you research them.
The target goal
The goal is to be able to format the code below in a way that the user will be able to understand by using all the methods above after explaining them.
The output of this code must be Name: Awonke | Email: awonke@contawo | Password: 123 | Score: 123.89
Comma separation
This is the most common way of formatting strings in python. You just separate them by a comma then your done. Here is an example below:
The output of this code will be 1 2 3, which is strange because, if you notice, there are spaces in between. What could be causing these spaces?Python has arguments that you can pass on to the print function, and these arguments are called sep=”” and end="". You can learn more about them through research, after all, you're a programmer, and that’s what programmers do.By default, Python declares the sep argument on every print function you use. The default looks like this: sep=” ", and to disable the default, you can add your own sep=””. Here is what I mean in a practical sense.Just remove the spaces in the sep="".By default, you will not see the sep=”", but that does not mean it is not there, just like that bug that is chilling in your projects as we speak.
The target goal
Now that we know how to use this method, let us reach our goal of formatting the user data that we got from whatever source.
I have removed the default spaces caused by the sep.I created my own spaces instead, but you can do it in your own way, as long as it works 🥲.I rounded off user_score using the round() function provided by Python globally in order to achieve the goal.I also converted the number (floats and integers) into a string because Python says so 🥲. This method works with strings only hence you need to convert everything else to a string, like I did.Please note:
When you separate your strings with commas, Python treats them as individual strings, hence the sep works on them. With the method below, it is different.
Concatenation
This method involves the addition of strings instead of separating by commas. By adding them together, you are basically combining them into one string. Here is an example:
The output of the code above will return 123. What does this mean? Why are there no spaces in between? Remember that the sep works on two or more strings.When you add or concatenate (same word as add) different strings, you are making them into one string, for example:The output here will be True because adding strings together is just the same as combining them together into one.
The target goal
Now that we have learned how to use this addition method, let us attempt to reach our goal by formatting the data.
In this case, there was no need to remove the default spacing because I added the strings.I just removed the commas from the previous method and added the addition.I also rounded off the user_score and converted the numbers into strings. Why? Python says so 🥲.Please note:
You can only add strings together. If you want to add a number for this instance, you will have to convert that number into a string using the str(number) built-in function.
Internal formatting
This method, including the ones below, will use the Concatenation method, but in a more advanced and simpler way. This method allows you to directly put your variables inside the string. Here is how you can do it:
The above code with print Name: Contawo, version: 1With this method, we do not need to convert the number into a string, which is more nice and simple compared to the above methods.If you notice, we have the letter f before the quotes. What does it mean? Does it need to be there?
The importance of the “f”
For this method to work, there must always be a f in front of the string, like you see in the example above. If you forget the f, the output will be:
Instead of getting the actual variables displayed, This is because Python will just treat it as a string if you do not include the f. By the way, the f stands for format.
The target goal
Since we now know how to use this method, let us reach our goal of formatting the data.
Above, I rounded off the user_score to achieve our goal. As you can see, there was no need for me to convert the numbers to strings.Please note:
With the method above, you do not need to convert any data format to a string, whether it is a number or an array; just put it in without any worry, like a baby swallowing dirt.
External formatting
This method is the same as the one above in terms of approach, but it is different in terms of syntax. Instead of putting the variables directly in the string, we put them outside. You need to be very careful with the order in which you put your variables. What do I mean?
Instead of using f in the beginning, we write it at the end and in full (format, not f).If you also notice, our variables are no longer placed inside, like in the method above; they are now outside the format brackets.The { } brackets represent the string according to the order they appear in relation to the order in which they are placed in the format brackets; hence, the order matters. What do I really mean by this?
Why does the order matter?
Let us break the order matters situation in a more practical way:
The above code will print First: one, Second: two. How?The first { } will match the first variable in the .format() brackets, which is first in this situation.The second { } from the left will match the second variable in the .format() brackets, which is second in this situation. Hence, I said that order matters here.The above code will print First: two, Second: one. How?The first { } will match second because second is the first variable in the .format() brackets.The second { } will match first because first is the second variable in the .format() brackets.
The target goal
Now that we understand how to use this method, let us reach our goal of formatting the data.
Do not forget to round off the user_score to achieve our goal.Please note:
Always remember when using the method above that order matters. Do not forget this or logic errors will be your friend.
Percentage formatting
Finally, we are at the last method. This method is similar to the method above in terms of approach but different in terms of implementation. This is the method with super powers because it enables you to round off float numbers without using the round() function on top of the formatting powers.
The syntax
Instead of using .format() like we did on the previous method, we use % and then add the brackets.Instead of using { }, we represent the variables according to their data type; in the code above, the %s represents a string and the %d represents an integer. What about the others? Let me make a table.Please note:
Just as with the method we used above, the order also matters for this method. Always keep this in mind when using this method and the previous one.
Representing data types
The table below shows how to represent each data type when formatting the string using this method.
Table content
Filter table
Data type
Representation
Example
string
%s
“String: %s” % (”example”)
integer
%d
”Integer: %d” % (123)
float/decimal
%f
”Float: %f” % (10.29)
char/character
%c
”Char: %c” % (”E”)
Feature in progress
Rounding off
Let us say, in the case of a float, we want to round off a number to 3 decimal places. How do we achieve this with this method?
The code above will print Rounded off: 12.324If you can see that after the % we have a dot and a number, this is how you round off a float number. You add a . after the %, then specify the decimal places that you want to round off to; in our case, it was 3.
The target goal
Now that we can format using the method above, let us reach our target goal of formatting the user data.
Instead of using the round() function, I used a different method that I have stated above.
The tasks
I have been talking (writing, actually), and you have been reading. It is time to get your hands dirty and learn through doing.
What will be the output of this code? And why is that the case? 😄 I would love to hear your answer on the comments.
Conclusion
String formatting in Python is very important to know, especially if you will be using Python a lot. This is one of those things that you really have to know. I did not want to give you one method because I believe that, as a programmer, you must have a different approach to solving a problem. I hope I helped you; if not, feel free to add a comment because, by doing so, you are also helping others who might have the same question. Happy stressful coding and enjoy the anxiety 😄.
Comments
0
Resources
Related
No comments yet. 🧐 I would love to hear your thoughts on how to format string in python