Python String – Python has become a very popular programming language for application development. We will continue to explore string variables and how to manipulate them.
Chapter before : Python Tutorial – Variables (2)
Python String
We have seen a string variable in the previous chapter, but there is much more to cover on this topic.
Concatenation It is possible, for example, to concatenate multiple strings using the + character.
Here is an example:
myStreet = "Rue de la Paix" newLine = "\n" myCity = "Paris" print(myStreet + newLine + myCity)
This will display:
Peace Street Paris
However, if you want to use an integer or a decimal variable for concatenation, you will get an error message. To make this possible, you should use the str() function to convert it to a string.
myWeight = 86.5 print("I weigh " + str(myWeight) + " Kg.")
This will result in:
I weigh 86.5 Kg.
Asking a Question to an user
In Python, it is possible to ask the user a question and store their response in a variable using the input() function.
For example, you can try:
yourAge = input("What is your age?") print("You are " + yourAge + " years old")
The program will pause on the first line until the user enters a number and presses “Enter” to confirm.
Keep in mind that to perform mathematical operations, you need to convert the provided age from a string to an integer, like this: yourAge = int(yourAge).
Going Further with the print Function
The print function can also display integer or decimal numbers directly using the comma separator. In functions, the comma is used to separate the parameters expected by a function.
myAge = 40 print("I am", myAge, "years old")
With the comma, there is no need to use the str() function to convert to a string.
You can also use specific parameters in the print() function that might interest you, such as:
end
to specify how each print output concludes.sep
to define a separator between each displayed print parameter.
Here is an example:
day = 31 month = 12 year = 2023 print("Christmas will be on:", day + "/" + month + "/" + year, end=' ') print(day, month, year, sep="/")
Conclusion – Python String
We will delve deeper into variables in the next chapter, as they still hold many secrets.
Be the first to comment