Python | Data Types | Strings

A string is any value within quotation marks. For example “Dan”, “Attention, it bites!”, ‘Dan is from Romania’, are all strings. Example:

message = “Hi there!”

Strings can be added together the same way numbers can by using the + operator. Example:

name = “Dan “
fruit = “likes mangoes.”
message = name + fruit

Here we declared two variables, name and fruit. The third variable, message, is the name + fruit. The print(message) prints the value of the variable message on the screen.

Python data types - strings

You can format strings using special characters. The special character is %s. It acts like a placeholder. He is how it works!

name = “Dan”
age = “40”
message = “My name is %s and I am %s.”%(name,age)

Here is what you get.

Data Types placeholder Python

Let’s take a look at message = “My name is %s and I am %s.”%(name,age).

The first %s is actually the value of an unspecified variable. The second %s is the value of another unspecified variable. After the quotation marks are closed we specify what % actually is by using %(name,age).

It says that the first % is the value of the variable name and the second % is the value of the variable age.

You can format integers in the same way by using %d as a placeholder. For floats you have to use %.4.2f. The 4 is the total length of the float and 2 represents the number of decimals.

Leave a Reply