String Operations in Python
Python uses a built-in data type to represent strings of characters (such as words and sentences). These strings act as other types of data in Python, in that programmers can assign strings to variables, can add strings together (an operation called concatenation) and compare them like integers or decimal numbers. Python programmers can also check for values in strings, search for the location of a value in a string and copy substrings from a larger strings.
-
The in, not in, and index() Operations
-
A programmer can check for values inside a string using built in functions provided by Python. The "in" operator checks a string, and returns a True or False value depending if character exists in the string. The opposite operator is the "not in" operator, which returns a True value if an element is NOT in a string, and false if it is. The "index()" method checks for a value, and upon finding the first instance of the value returns the index as an integer. Consider this example:
>>>s = "A String"
>>>A in s
True
>>>z not in s
True
>>>a in s
False
>>>s.index(S)
2
Concatenation
-
Concatenation means to add one string to the end of another string. In Python, concatenation is represented by an addition symbol ("+"). In essence, concatenation means to add sentences together. For example, this code creates three strings and concatenates them, one at the end of the other.
>>>s1 = "This is "
>>>s2 = "example "
>>>s3 = "a string "
>>>s1 = s1 + s3
>>>s1
This is a string
>>>s1 = s1 + s2
>>>s1
This is a string example
-
String Comparisons
-
Much like the addition symbol adds sentences the same way it adds numbers, the programmer can compare strings much in the same way he can compare numbers. This is accomplished with the normal comparison operators such as greater than (>), less than (<), equal to (==), and not equal to (!=). Consider this example, in which two strings are compared, resulting in True or False values:
>>>a = 'Hello'
>>>b = 'Goodbye'
>>>a > b
True
>>>a < b
False
>>>a == b
False
>>>a != b
True
Slicing
-
"Slicing" is an operation that returns a substring from the longer string. Slicing uses a special slice "notation," in which a pair of brackets follows the string name, with two integer values separated by a colon. The programmer denotes what the starting index is on the left side of the colon, and the ending index on the right. Here are some example slices:
>>>s = "This is a string example"
>>>s[1:4] // strings characters begin at index 0
'his '
>>>s[0:] //Leaving the right empty takes the rest of the string after the start index
'This is a string example'
>>>s[:7] //Leaving the left side empty takes everything from 0 to the right index
'This is'
-
References
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images