Размер шрифта
-
+

Python Handbook For Beginners - стр. 8


print("Super Cat" +" saves the day!")


Have you fixed that? Hit run again.

5 Strings Concatenation And Variables

Note that we can concatenate a string only with another string. Or a string-formatted value. For example, if we created a variable and assigned a string-formatted value to it, we can also concatenate such a variable with another string. In the example below, I created a variable (hero) and assigned a string-formatted value (Super Cat) to it. Then I displayed this value in concatenation with another string (VS Duper Dog).


hero = "Super Cat"

print(hero + " VS Duper Dog")


Try this code out. What message do you get? Now, change the code as you like. You can even concatenate more than two strings! Alter and run the code. See how the output changes!

6 String Formatting

Now let's talk about what string formatting is. We have already learned how to concatenate strings using the + operator. The + operator can only concatenate a string with another string. But what if we want to concatenate a string with something that doesn't have a string format? In this case, we use string formatting to turn a value that doesn't have a string format into a string-formatted value. To do so, we need two things:

The format() method to format the non-string value and insert it inside the string's placeholder.

The placeholder itself – {} for the non-string value.

Let me show you how it works in the example below:


print("My name is Super Cat, and I'm {} years old".format(2))


Please write this code into the console and run it. Here is the result you should get:



Now let's break it down.

1) We created a placeholder in our string. You can identify it by the curly brackets – {}. This placeholder is for the age of the Super Cat, which has a numeric value.

2) After the string end, we put the format() method and passed our numeric value, 2, to its brackets.

3) As a result of this operation, Python took our numeric value, formatted it into a string value, and passed it to the placeholder. So now it belongs to the entire string in the same string format.

4) After that, we displayed the entire string using the print function.

I encourage you to play with the given code and experiment with placeholders and values you pass to the format() method. Here is another way to accomplish the above exercise:


print("My name is {}, and I'm {} years old". format("Super Cat",2)


Can you explain how it works now? Can you come out with your ideas?

7 Wrapping Up Chapter Four

In chapter four, we have accomplished the following:

1) Learned what are strings in Python;

Страница 8