Strings

Strings in programming are simply text; either individual characters, words, phrases, or complete sentences. They are one of the most common elements to use when programming, at least when it comes to interacting with the user. Because they are so common, they are a native data type within Python, meaning they have many powerful capabilities built in. Unlike other languages, you don't have to worry about creating these capabilities yourself.

Strings in Python are different than in most other languages. First off, there are no char types, only single character strings (char types are single characters, separate from actual strings, used for memory conservation). Strings also can't be changed in-place; a new string object is created whenever you want to make changes to it, such as concatenation. This means you have to be aware that you are not manipulating the string in memory; it doesn't get changed or deleted as you work with it. You are simply creating a new string each time.

Empty strings are written as two quotes with nothing in between. The quotes used can be either single or double; my preference is to use double quotes, since you don't have to escape the single quote to use it in a string. That means you can write a statement like the following:

"And then he said, 'No way', when I told him."

If you want to use just one type of quote mark all the time, you have to use the backslash character to escape the desired quote marks so Python doesn't think it's at the end of the phrase, like this:

"And then he said, "No way", when I told him."

Triple quoted blocks are for strings that span multiple lines, as shown in Chapter 1, The Fundamentals of Python. Python collects the entire text block into a single string with embedded newline characters. This is good for things like writing short paragraphs of text; for example, instructions, or for formatting your source code for clarification.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset