Back to: Python Programming
A ‘string’ is a series of characters that can be assigned to a variable. Being able to work with parts of a string, look for specific characters, truncate, count the number of characters are all things we might want to do to allow us to validate input. For instance, an email address must contain the ‘@’ symbol and a mobile phone number should have 10 digits.
The operations we can perform on strings use functions and methods.
The ‘len’ function finds the number of characters in a string, try:
name = "Benedict"
length = len(name) # <-- len is a function
print(length)
If we now type our variable followed by a ‘.’, we have access to a set of ‘methods’.
Examples of methods include:
find() Searches the string for a specified value and returns it’s position
count() Returns the number of times a specified value occurs in a string
startswith() Returns true if the string starts with the specified value
a full list of Python String Methods can be found at:
https://www.w3schools.com/python/python_ref_string.asp
find()
The ‘find()’ method:
name = "Benedict"
# To find the first occurrence of letter "c"
# use name.find("c") - result will be 6 because
# the first position is 0
result = name.find("c")
print(result)
The result here will be 6. Python treats the first position as 0 so “c” occurs in position 6.
Test this by changing the code to name.find(“B”)
rfind()
The ‘rfind()’ method will find the position of the last instance of the character.
For:
Name = “Benedict” ⇐ the first instance of “e” is position 1, the last instance is in position 3
name = "Benedict"
# To find the last occurrence of letter "e"
# use name.rfind("e") - result will be 3
result = name.rfind("e")
print(result)
If there are no results, the answer returned will be -1.
The ‘capitalize()’ method:
Will make the “first” letter in the string a capital letter:
name = "benedict"
# To convert the first letter of a string
# a capital letter:
result = name.capitalize()
print(result)
upper()
The ‘upper()’ method converts ALL characters in a string to UPPERCASE.
name = "benedict"
# To convert all characters of a string to UPPERCASE:
result = name.upper()
print(result)
The ‘lower()’ method converts ALL characters in a string to lowercase.
name = "MAKE ME LOWERCASE"
# To convert all characters of a string to lowercase:
result = name.lower()
print(result)
isdigit()
The ‘isdigit()’ method returns True or False if a string returns only digits
name = "0398761234"
result = name.isdigit()
print(result)
The ‘isdigit()’ method returns False if there are ANY spaces or non-numeric values.
The ‘isalpha()’ method returns True or False if a string returns only alphabetic characters. Any spaces, numbers or anything other than the 26 letters of the alphabet will return a False.
The ‘count()’ method lets us count the number of specific items in the string.
phone = "03 9876 1234"
# To count the spaces in the string (there are 2):
result = phone.count(" ")
print(result)
The ‘replace()’ method is a very useful tool allowing us to replace a specific character with something else. If we wanted a phone number entered but want to remove any spaces
phone = input("Enter your phone number: ")
# To count the spaces in the string:
result = phone.replace(" ", "" )
print(result)
Exercise:
Write code asking your user for a username, then validate the username to ensure they have complied with the username format you require.
- Username must have 4 to 12 characters
- Username must not contain spaces
- Username must not contain digits
Solution:
username = input("Enter a username: ")
if len(username) < 4 or len(username) > 12:
print("Your username should be 4 - 12 characters long!")
elif username.isalpha():
print("Your username is verified")
else:
print("Your username can only contain letters!")
Alternate solution:
username = input("Enter a username: ")
if len(username) < 4 or len(username) > 12:
print("Your username should be 4 - 12 characters long!")
elif not username.find(" ") == -1:
print("Your username can't contain spaces")
elif not username.isalpha():
print("Your username can only contain letters!")
else:
print(f"Welcome {username}, account verified! ")
Which is the better solution?