Saturday, November 12, 2011

String operations - Part 1 of 3

Strings are sequences of characters. Python has a native string type that is used to hold character sequences.

The String data type in Python is immutable. This means that once a string is created, you cannot change it. You can make another string using operations on the string you created, but you cannot change the contents of a string.

More about this later.


We've created four (4) strings, a, b, c and d. And assigned some values to them. The first thing to notice is that you can use single (') or double (") quotes to delimit the string. For example, you might use double quotes if you have a single quote as part of the string as in the example below.


The second thing you'll notice is that the Python interpreter also displays the string with double or single quotes as necessary. This isn't very important, but notice when you use the print keyword to display the strings, the quotes aren't displayed.

The quotes are NOT part of the string. If you want to include quotes in your string, you would have to also include them inside the outside pair of quotes.

You can, surprisingly, use some of the mathematical operations on strings. Look at the following examples.


The "+" operator for strings represents concatenation. So, "jack" + "jill" becomes "jackjill" There are no spaces since the concatenation joins one string at the end of the other.

You can also see how a, b, c and d, "jack" "jill" "peter" and "wolf" are concatenated. If spaces are important in your programs, then you have to manually provide them.

The "*" operator for strings represents repetition. In the example a * 3 becomes "jackjackjack" The string "jack" is repeated three times.

We'll come back to strings later and do some more interesting things such as counting characters, extracting portions of the string, searching them and so on.

No comments:

Post a Comment