Manipulating Strings
Learn about the different types of operations that can be performed on strings.
We'll cover the following...
Strings
As we learned earlier, a string is a sequence of characters, and a character does not have to be a letter—it can be punctuation marks, a space, a hyphen, or any other character we can produce using a computer. A string can also contain digits.
The first thing we must understand is that a string only containing digits won’t be the same as if it were an integer. Take a look at the following code:
numberA = 1234numberB = "1234"
Notice the quotation marks around the digits in the last number. This turns it into a string. The first one, numberA
, will be of the integer type, so it can be used for counting
and other mathematical operations. For the computer, the second one is just as much a number as the word “dog” is a number—not at all.
When working with strings, there are several typical things we can do with them. Let’s take a look at some frequent string operations.
String concatenation
When we take two strings and add them together to form a new string, we call it concatenation. How this is done differs a bit from language to language, but we can often use the +
operator, as in the following example:
word = "day" + "break"print word
Here, we have two strings — "day"
and "break"
. The quotation marks tell us that they’re strings. They’ll now be concatenated into a new string that is stored in the ...