While we’ve used strings in many of our examples and some of out assignments so far, we’ve not actually worked too much with Strings.
Remember that a string is a collection of characters which are either taken as an input from a user, read from a text file, or enclosed within quotes within our program.
However, we’ve not done much with strings, other than input, print, and concatenation.
Iterating over a String
Iteration is the process of going through a string, letter by letter. In this first example, we’ll look at something basic like printing out the letters of a string, one at a time.
name = "Tom Morrow"
for ch in name :
print(ch)
Now you might want to know why you’d do something like that. Well, let’s say you wanted to count the number of times a letter occurs, for example the letter “O”, we’ll you can use the loop, and an internal if statement to find each letter, and count it.
name = "Tom Morrow"
count = 0
for ch in name :
if ch == "o" or ch == "O" :
count += 1
print("The letter 'O' occurs", count, 'times in the string', name)
Indexing a String
Another way to look at individual letters in a string, is to use an index. Just like with lists, we can use an index to examine an individual letter of a string. We will also use square brackets to check the index, and can have a negative index.
name = "Tom Morrow"
print(name[1])
print(name[-2])
If you pick an index which would not occur, you will get an IndexError exception that the program can catch if you code it with a try/except block.
Strings are Immutable
Despite what it might seem with things like concatenation, strings are actually immutable. When you concatenate, you actually create a new string that is a combination of those two strings – even if you use the += to concatenate a value.
That is why string concatenation is often considered to be slow. It’s because the system is removing one string, to build the new string from scratch. Since it has to define the new string, it takes time to process. Now building a single string isn’t probably a big deal, but if you had to update thousands of strings (for example, joining first and last names together for every student in school) it starts to add up.
String Slicing
Many languages have a way to get a “Sub-String” or part of a string. In Python, it uses slicing, just like you would slice a list. It follows the general form below:
string[start : end]
Start is the first character of the slice to be kept, and end is the index marking the end of the slice.
name = "Edgar Allan Poe"
middle_name = name[6:11]
print(middle_name) # prints Allan
If you leave off the first number, you start at the beginning and go to the end index. If you leave off the last number, you start at the start location, but go until the end of the string.
name = "Edgar Allan Poe"
first_name = name[:5]
last_name = name[12:]
print(first_name) # prints Edgar
print(last_name) # prints Poe
Odd Slicing Techniques
There are some odd things you can do with Slicing. For example, you can add a third number – which allows you to specify how many characters to skip between the characters shown.
example = "1234567890)(*&^%$#@!"
print(example[0:len(example):2]) # prints 13579)*^$@
print(example[0:len(example):3]) # prints 1470*%@
You can also skip the first character, and use a negative number, to move from the end of the string for your last character. However, this is rarely done in most circumstances.
Finding If a Sub String Exists
It is fairly common to know if a sub string exists within, or see if it is not within a larger string.
So a sub-string remember is just a part of a string.
Let’s say you had a string of names, and you wanted to see if a specific name was in the larger string. You could use the in
command to check.
completed = "John Sue Mary Jacob Katie Mike"
find_it = input("Enter the name of the person you are looking for: ")
if find_it in completed :
print(find_it, 'was found in the completed name section.')
else :
print(find_it, 'was not found.')
But what if you wanted to see if the person’s name (or other value) wasn’t in string? Well, you can use not in
.
completed = "John Sue Mary Jacob Katie Mike"
find_it = input("Enter the name of the person you are looking for: ")
if find_it not in completed :
print(find_it, 'has not completed this section yet.')
else :
print(find_it, 'was found in the list.')
Basic String Operations was originally found on Access 2 Learn