How to Count Common Character in a String in Python
In this tutorial, we’ll learn how to program "How to Count Common Characters in a String using Python." The focus will be on accurately counting the total number of common characters from a given input string. A sample program will be provided to demonstrate the process step-by-step, making it simple and easy to understand. So, let’s get started!
This topic is simple to understand. Just follow the instructions I provide, and you’ll be able to complete it with ease. The program I’ll demonstrate will show you the proper way to count common characters. I’ll also include a straightforward and efficient method to achieve this effectively. So, let’s start coding!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- def commonChar(str1,str2):
- return(len((set(str1)).intersection(set(str2))))
- while True:
- print("\n================= Count Common Character in a String =================\n\n")
- char1="SourceCodester"
- char2=input("Enter your string: ")
- char_find=commonChar(char1.lower(),char2.lower())
- print("No of common characters : ",char_find)
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- continue
This program calculates the number of common characters between a predefined string "SourceCodester" and a user-provided string. It first converts both strings to lowercase for case-insensitive comparison. Using Python's set data structure, it identifies the intersection of characters shared between the two strings and computes the length of this intersection to determine the count of common characters. The program repeats this process in a loop, allowing the user to enter multiple strings for comparison or exit the program based on their choice.
Output:
There you have it we successfully created How to Count Common Character in a String in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language
Add new comment
- 42 views