Strings in Python

 Strings in Python - Bytesize Python

Why Strings?

Strings can be useful when you need to use text within your program. Strings can be joined together, or parts can even be cut out. You'll find out the basics on how to use strings in your programs here.

Creating a String

To create a string, you can often assign it to a variable. A string might include letters, numbers, symbols or spaces. These are called characters. (You may have seen this in the Variables in Python or Data Types in Python page)



Adding strings

Adding numbers together results in another number. Similarly when adding strings, they simply join on to the end of the other.
You can also add a string in between  the variables.




Length of a string

The 'len()' function is used to find out the length of a string. Python counts all of the characters, including spaces, and gives the total number of characters.


Numbering characters

Each character in a string is allocated a number according to its position. The position number is called an index. Strings always start with the first character having an index of 0, and then going on from that. For example a character with the index of 4, with be the 5th letter in the word.
 C A T E R P I L L A  R
 0  1 2 3  4 5 6 7 8 9 10


Square brackets around an index can be used to pull out a particular letter from a string, as seen below.
Two Indexes can be used to  pull out part of a string or slice it. The last index you give will not be included, so in this example only indexes 1,2 and 3 will be shown. If you leave out the start or end index, python will automatically include the first or last index.





Apostrophes

 You may have noticed that I tend to put single quotation marks around my strings, however you can also use double quotation marks if you prefer. But if you choose to use single quotation marks like me, you may wonder how you can use apostrophes in strings. If you add a backslash before the apostrophe, python will interpret it as part of the string and not the end  of the string. This is called escaping it.






Popular Posts