Like a list, Strings are actually objects in Python. That means, the have methods attached to them, to help you work with them. Here we’re going to look at some common methods to see how you can use them.
Testing a String
The first set of methods we’re going to look at are tests. These will give you a Boolean value back letting you know if the condition is true. This condition can be used in a while loop, or if statement easily.
Test Method | Description |
.isalnum() | Is the string only composed of alphabetic letters and/or numbers. i.e. no special characters. |
.isalpha() | Is the string only composed of alphabetic letters. These may be upper or lower case letters. |
.isdigit() | Is the string composed of numeric digits (0-9). You can use this before you try to convert a string to a number to ensure that you can. |
.islower() | Similar to .isalpha(), however it is only looking for lower case letters. |
.isupper() | Similar to .isalpha(), however it is only looking for upper case letters. |
.isspace() | Checks to see if the string only contains white space characters such as the Tab(\t), Space, New Line (\n),etc. |
The program below lets you test these out.
def main():
# get a string from the user
tester = input("Enter a string to test: ")
print("You entered," tester, "we can tell the following:")
#test to run
if tester.isalnum() :
print("This string is only made up of letters and numbers.")
if tester.isdigit() :
print("This string is only made up of numeric digits.")
elif tester.isalhpa() :
print("This string is only made up of alphabetic characters")
if tester.isupper() :
print("This string is only upper case characters.")
elif tester.islower() :
print("This string is only lower case characters.")
elif tester.isspace() :
print("This string is only white space.")
else :
print("None of the set conditions is true, which means there is at least one special character.")
main()
Notice how there are if statements dependent upon one another. For example, we only test isdigit() if isalnum() is true, because you cannot be a digit and not true under isalnum(). Likewise, when we test isalpha() under an elif, because if the string is a digit, it cannot be an alphabetical character string, but it must be contained within the test for isalnum().
We only test to see if they are upper or lower case is the string is only made up of alphabetic characters.
By doing the test this way, we optimize the organization of the tests, don’t perform unnecessary tests and speed up the processing of our application.
Modification Methods
There are numerous methods that let you modify a string. They will return a value that is the modified string. This means you change the value of the string you have to use the format of string = string.<modification>()
.
The lower()
method lets you reset all alphabetic characters to their lower case equivilients. Likewise, upper()
changes every thing to upper case.
my_str = 'aBcDeFgH'
print("My string is:", my_str)
print("All upper case it is:", my_str.upper())
print("All lower case it is:", my_str.lower())
These methods are helpful if you want to make a case insensitive condition check.
again = input("Do you wish to continue (Y/N)")
if again == 'Y' or again == 'y':
# do some stuff
#this can be simplified to
if again.lower() == 'y':
# do some stuff
Removing White Space
The method strip()
removes all leading (at the front of the string) and trailing (at the end of the string) white space for a string. But if you only want to remove leading white spaces use the lstrip(
) method, or rstrip()
for trailing white space characters.
With all of three methods, you can pass a character, to remove only that character, instead of all white space characters.
Find and Replace
Working with strings means having to deal with finding information and changing it. Now remember, strings are immutable, so we are creating a new string when we make a change.
The find((<sub string>)
method, let’s us find a sub-string within a string. This is very similar to the in
command that we looked at earlier. However, instead of returning a Boolean value, it returns the index at where the string was found. This makes it easier to slice a string. If find cannot locate the sub-string, then it returns a value of -1.
Similar to find, you have startswith(<sub string>)
and endswith(<sub string> )
. These two methods lets you test to see if your string starts or ends with a specific sub-string and returns a true/false Boolean value.
For example, you might want to determine if a person is a Dr., so you can specify full_name.startswith('Dr.')
or if they are a junior, full_name.endswith('Jr.')
.
def main() :
lyrics = "Jeremiah was a bullfrog, was a good friend of mine. Never understood a single word he said."
find_it = input("What word(s) are you looking for? ")
if lyrics.find(find_it) != -1 :
# the word(s) were found
print(find_it, "was found in the suggested lyrics.")
if lyrics.startswith(find_it) :
print("The lyrics even start with that phrase.")
elif lyrics.endswith(find_it) :
print("The lyrics end with that phrase.")
else :
print(find_it, "was not in the lyrics we searched.")
main()
Python String Built in Functions was originally found on Access 2 Learn