Jens Braun - Learn Python quick

Здесь есть возможность читать онлайн «Jens Braun - Learn Python quick» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Learn Python quick: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Learn Python quick»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

learn Python quick is the world's best-selling guide to the Python programming language. This good introduction to programming with Python will have you writing programs, solving problems, and building things that work in no time.You'll learn basic programming concepts like variables, lists, classes, and loops, and practice writing clean code with exercises on each topic. You'll also learn how to make your programs interactive and how to safely test your code before incorporating it into a project.

Learn Python quick — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Learn Python quick», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

We can combine multiple substrings by using the concatenate sign (+). For instance, “Peter” + “Lee” is equivalent to the string “PeterLee”.

Built-In String Functions

Python includes a number of built-in functions to manipulate strings. A function is simply a block of reusable code that performs a certain task. We’ll discuss functions in greater depth in Chapter 7.

An example of a function available in Python is the upper() method for strings. You use it to capitalize all the letters in a string. For instance, ‘Peter’.upper() will give us the string “PETER”. You can refer to Appendix A for more examples and sample codes on how to use Python’s built-in string methods.

Formatting Strings using the % Operator

Strings can also be formatted using the % operator. This gives you greater control over how you want your string to be displayed and stored. The syntax for using the % operator is

“string to be formatted” %(values or variables to be inserted into string, separated by commas)

There are three parts to this syntax. First we write the string to be formatted in quotes. Next we write the % symbol. Finally, we have a pair of round brackets ( ) within which we write the values or variables to be inserted into the string. This round brackets with values inside is actually known as a tuple, a data type that we’ll cover in the chapter later.

Type the following code in IDLE and run it.

brand = ‘Apple’

exchangeRate = 1.235235245

message = ‘The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR’ %(brand, 1299, exchangeRate)

print (message)

In the example above, the string ‘The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR’ is the string that we want to format. We use the %s, %d and %4.2f formatters as placeholders in the string.

These placeholders will be replaced with the variable brand, the value 1299 and the variable exchangeRate respectively, as indicated in the round brackets. If we run the code, we’ll get the output below.

The price of this Apple laptop is 1299 USD and the exchange rate is 1.24 USD to 1 EUR

The %s formatter is used to represent a string (“Apple” in this case) while the %d formatter represents an integer (1299). If we want to add spaces before an integer, we can add a number between % and d to indicate the desired length of the string. For instance “%5d” %(123) will give us “ 123” (with 2 spaces in front and a total length of 5).

The %f formatter is used to format floats (numbers with decimals). Here we format it as %4.2f where 4 refers to the total length and 2 refers to 2 decimal places. If we want to add spaces before the number, we can format is as %7.2f, which will give us “ 1.24” (with 2 decimal places, 3 spaces in front and a total length of 7).

Formatting Strings using the format() method

In addition to using the % operator to format strings, Python also provides us with the format() method to format strings. The syntax is

“string to be formatted”.format(values or variables to be inserted into string, separated by commas)

When we use the format method, we do not use %s, %f or %d as placeholders. Instead we use curly brackets, like this:

message = ‘The price of this {0:s}laptop is {1:d}USD and the exchange rate is {2:4.2f}USD to 1 EUR’.format(‘Apple’, 1299, 1.235235245)

Inside the curly bracket, we first write the position of the parameter to use, followed by a colon. After the colon, we write the formatter. There should not be any spaces within the curly brackets.

When we write format(‘Apple’, 1299, 1.235235245), we are passing in three parameters to the format() method. Parameters are data that the method needs in order to perform its task. The parameters are ‘Apple’, 1299 and 1.235235245.

The parameter ‘Apple’ has a position of 0,

1299 has a position of 1 and

1.235235245 has a position of 2.

Positions always start from ZERO.

When we write {0:s}, we are asking the interpreter to replace {0:s} with the parameter in position 0 and that it is a string (because the formatter is ‘s’).

When we write {1:d}, we are referring to the parameter in position 1, which is an integer (formatter is d).

When we write {2:4.2f}, we are referring to the parameter in position 2, which is a float and we want it to be formatted with 2 decimal places and a total length of 4 (formatter is 4.2f).

If we print message, we’ll get

The price of this Apple laptop is 1299 USD and the exchange rate is 1.24 USD to 1 EUR

Note: If you do not want to format the string, you can simply write

message = ‘The price of this {} laptop is {} USD and the exchange rate is {} USD to 1 EUR’.format(‘Apple’, 1299, 1.235235245)

Here we do not have to specify the position of the parameters. The interpreter will replace the curly brackets based on the order of the parameters provided. We’ll get

The price of this Apple laptop is 1299 USD and the exchange rate is 1.235235245 USD to 1 EUR

The format() method can be kind of confusing to beginners. In fact, string formatting can be more fanciful than what we’ve covered here, but what we’ve covered is sufficient for most purposes. To get a better understanding of the format() method, try the following program.

message1 = ‘{0} is easier than {1}’.format(‘Python’, ‘Java’)

message2 = ‘{1} is easier than {0}’.format(‘Python’, ‘Java’)

message3 = ‘{:10.2f} and {:d}’.format(1.234234234, 12)

message4 = ‘{}’.format(1.234234234)

print (message1)

#You’ll get ‘Python is easier than Java’

print (message2)

#You’ll get ‘Java is easier than Python’

print (message3)

#You’ll get ‘ 1.23 and 12’

#You do not need to indicate the positions of the parameters.

print (message4)

#You’ll get 1.234234234. No formatting is done.

You can use the Python Shell to experiment with the format() method. Try typing in various strings and see what you get.

Конец ознакомительного фрагмента.

Текст предоставлен ООО «ЛитРес».

Прочитайте эту книгу целиком, купив полную легальную версию на ЛитРес.

Безопасно оплатить книгу можно банковской картой Visa, MasterCard, Maestro, со счета мобильного телефона, с платежного терминала, в салоне МТС или Связной, через PayPal, WebMoney, Яндекс.Деньги, QIWI Кошелек, бонусными картами или другим удобным Вам способом.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Learn Python quick»

Представляем Вашему вниманию похожие книги на «Learn Python quick» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Learn Python quick»

Обсуждение, отзывы о книге «Learn Python quick» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x