08-22-2022, 02:10 PM
How to Ignore Case in Strings
5/5 – (1 vote)
Problem Formulation and Solution Overview
In this article, you’ll learn how to ignore (upper/lower/title) case characters when dealing with Strings in Python.
The main reason for ignoring the case of a String is to perform accurate String comparisons or to return accurate search results.
For example, the following three (3) Strings are not identical. If compared with each other, they would return False.
This is because each character in the ASCII Table assigns different numeric values for each key or key combination on the keyboard.
This article outlines various ways to ignore the case of Strings.
Question: How would we write code to compare Strings?
We can accomplish this task by one of the following options:
Method 1: Use lower() and a lambda
This method uses and a to convert a of Strings to lower case to search for an Employee.
Above declares a of Rivers Clothing Employees. If we were searching for an Employee, such as , using this List, no results would return as and are not the same. Let’s fix this issue.
Info: A function is a one-liner that, in this case, converts each List element in to lower case. Then, converts to a object and back to a https://blog.finxter.com/python-lists/List. The output saves to and is output to the terminal.
If a comparison was made now, it would find the correct Employee.
Match Found!
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkBg4n52XoUQ%2Fhqdefault.jpg)
Method 2: Use upper() and List Comprehension
This method uses and a list comprehension to convert a List of Strings to upper case and search for an Employee.
Above declares a List of the Top five (5) Beauty Brands in the world. If we were searching for a Company, such as, using this List, no results would return as and are not the same. Let’s fix this issue.
Ahttps://blog.finxter.com/a-simple-introd...in-python/List Comprehension is called and converts each element in to upper case. The results are saved to and output to the terminal.
If a comparison was made now, it would find the correct Brand.
Murad Found!
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaBC0VhpXkOQ%2Fhqdefault.jpg)
Method 3: Use title()
This method uses to convert each word in a String to upper case. Great use of this is to convert a Full Name to title case. This ensures both the First, Middle and Last Names are as expected.
Above accepts a string, appends the method to the string, saves it to and outputs to the terminal.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-UkcLQxzPA4%2Fhqdefault.jpg)
Method 4: Use casefold() and a Dictionary
This method uses to convert a String to lower case. This method does more than : it uses Unicode Case Folding Rules.
Above creates a quote in German and saves it to. This ensures all characters are correctly converted to lower case, thus making a caseless match.
What does this say?
Method 5: Use lower() and Dictionary Comprehension
This method uses Use to convert Dictionary values into lower case using Dictionary Comprehension.
Above creates a Dictionary containing Rivers Employees Names and associated Job Title. This saves to.
Next, Dictionary Comprehension is used to loop through the values in the key:value Dictionary pairs and convert the values to lower case. The output saves to and is output to the terminal.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTlEC5Jx72Uc%2Fhqdefault.jpg)
Bonus: CSV Column to title() case
In this Bonus section, a CSV file you are working with contains a column of Full Names. You want to ensure all data entered in this column is in case. This can be accomplished by running the following code.
Contents of file
FID |
Full_Name
30022145 |
sally jenkins
30022192 |
joyce hamilton
30022331 |
allan thompson
30022345 |
harry stiller
30022157 |
ben hawkins
Above imports the Pandas library. For installation instructions, click here.
Next, the file (contents shown above) is read and saved to the DataFrame .
The highlighted line directly accesses all values in the column and converts each entry to case. This saves back to and is output to the terminal.
|
FID |
Full_Name
0 |
30022145 |
Sally Jenkins
1 |
30022192 |
Joyce Hamilton
2 |
30022331 |
Allan Thompson
3 |
30022345 |
Harry Stiller
4 |
30022157 |
Ben Hawkins
Note: Don’t forget to save the DataFrame to keep the changes.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-JKVy_HliQE%2Fhqdefault.jpg)
Summary
These six (6) methods of ignoring cases in Strings should give you enough information to select the best one for your coding requirements.
Programmer Humor
Question: Why do programmers always mix up Halloween and Christmas?
Answer: Because Oct 31 equals Dec 25.
(If you didn’t get this, read our articles on the and Python built-in functions!)
5/5 – (1 vote)
Problem Formulation and Solution Overview
In this article, you’ll learn how to ignore (upper/lower/title) case characters when dealing with Strings in Python.
The main reason for ignoring the case of a String is to perform accurate String comparisons or to return accurate search results.
For example, the following three (3) Strings are not identical. If compared with each other, they would return False.
Code:
when life gives you lemons, make lemonade. WHEN LIFE GIVES YOU LEMONS, MAKE LEMONADE.When Life Gives You Lemons, Make Lemonade.This is because each character in the ASCII Table assigns different numeric values for each key or key combination on the keyboard.
This article outlines various ways to ignore the case of Strings.
Question: How would we write code to compare Strings?We can accomplish this task by one of the following options:
- Method 1: Use a and aCode:
lower()Code:lambda
- Method 2: Use andCode:
upper()Code:List Comprehension
- Method 3: Use Code:
title()
- Method 4: Use Code:
casefold()
- Method 5: Use and Dictionary ComprehensionCode:
lower()
- Bonus: Convert CSV of Full Names to title case
Method 1: Use lower() and a lambda
This method uses
Code:
lower()Code:
lambdaCode:
ListCode:
staff = ['Andy', 'MAci', 'SteVe', 'DarCY', 'Harvey']
staff_lower = list((map(lambda x: x.lower(), staff)))
print(staff_lower)Above declares a
Code:
ListCode:
DarcyCode:
DarcyCode:
DarCY
Info: A Code:
lCode:
aCode:
mbdaCode:
staffCode:
map()Code:
staff_lowerCode:
['andy', 'maci', 'steve', 'darcy', 'harvey']If a comparison was made now, it would find the correct Employee.
Code:
if ('Darcy'.lower() == staff_lower[3]): print('Match Found!')Match Found!
Method 2: Use upper() and List Comprehension
This method uses
Code:
upper()Code:
brands = ['ChaNnel', 'CLINique', 'DIOR', 'Lancome', 'MurAD']
brands_upper = [x.upper() for x in brands]
print(brands_upper)Above declares a List of the Top five (5) Beauty Brands in the world. If we were searching for a Company, such as
Code:
ChannelCode:
ChannelCode:
ChaNnelAhttps://blog.finxter.com/a-simple-introd...in-python/List Comprehension is called and converts each element in
Code:
brandsCode:
brands_upperCode:
['CHANEL', 'CLINIQUE', 'DIOR', 'LANCOME', 'MURAD']If a comparison was made now, it would find the correct Brand.
Code:
my_fav = 'Murad'
if (my_fav.upper() == brands_upper[4]): print(f'{my_fav} Found!')Murad Found!
Method 3: Use title()
This method uses
Code:
title()Code:
full_name = 'jessica a. barker'.title()
print(full_name)Above accepts a string, appends the
Code:
title()Code:
full_nameCode:
Jessica A. BarkerMethod 4: Use casefold() and a Dictionary
This method uses
Code:
casefold()Code:
lower()Code:
phrase = 'Nichts ist unmöglich für den Unwilligen!'
cfold = phrase.casefold()
print(cfold)Above creates a quote in German and saves it to
Code:
phraseCode:
nichts ist unmöglich für den unwilligen!What does this say?
Method 5: Use lower() and Dictionary Comprehension
This method uses Use
Code:
lower()Code:
employees = {'Sandy': 'Coder', 'Kevin': 'Network Specialist', 'Amy': 'Designer'}
result = {k: v.lower() for k, v in employees.items()}
print(result)Above creates a Dictionary containing Rivers Employees Names and associated Job Title. This saves to
Code:
employeesNext, Dictionary Comprehension is used to loop through the values in the key:value Dictionary pairs and convert the values to lower case. The output saves to
Code:
resultCode:
{'Sandy': 'coder', 'Kevin': 'network specialist', 'Amy': 'designer'}Bonus: CSV Column to title() case
In this Bonus section, a CSV file you are working with contains a column of Full Names. You want to ensure all data entered in this column is in
Code:
title()Contents of
Code:
finxter_users.csvFID |
Full_Name
30022145 |
sally jenkins
30022192 |
joyce hamilton
30022331 |
allan thompson
30022345 |
harry stiller
30022157 |
ben hawkins
Code:
import pandas as pd users = pd.read_csv('finxter_users.csv')
users['Full_Name'] = users['Full_Name'].str.title()
print(users)Above imports the Pandas library. For installation instructions, click here.
Next, the
Code:
finxter_users.csvCode:
usersThe highlighted line directly accesses all values in the
Code:
users['Full_Name']Code:
title()Code:
users['Full_Name']|
FID |
Full_Name
0 |
30022145 |
Sally Jenkins
1 |
30022192 |
Joyce Hamilton
2 |
30022331 |
Allan Thompson
3 |
30022345 |
Harry Stiller
4 |
30022157 |
Ben Hawkins
Note: Don’t forget to save the DataFrame to keep the changes.Summary
These six (6) methods of ignoring cases in Strings should give you enough information to select the best one for your coding requirements.
Programmer Humor
Question: Why do programmers always mix up Halloween and Christmas?
Answer: Because Oct 31 equals Dec 25.(If you didn’t get this, read our articles on the
Code:
oct()Code:
int()
