Introduction
In this project, you will learn how to extract numbers greater than 5 from a text file and print them out.
👀 Preview
$ python FindDigits.py
876
🎯 Tasks
In this project, you will learn:
- How to open a text file and read its contents
- How to extract specific numbers from a string
- How to concatenate the extracted numbers into a new string
- How to print the extracted numbers
🏆 Achievements
After completing this project, you will be able to:
- Manipulate strings and extract specific data from them
- Write a Python script to automate a simple data processing task
- Apply your knowledge of file handling and string operations in Python
Open the String.txt File and Read the String
In this step, you will learn how to open the String.txt file and read the string.
- Open your text editor and create a new file called
FindDigits.pyin the/home/labex/projectdirectory.
cd /home/labex/project
touch FindDigits.py
- In the
FindDigits.pyfile, use theopenfunction to open theString.txtfile in the same directory and read the string.
## Open the String.txt file in the same directory and read the string
with open("String.txt", "r") as f:
string = f.read()
The with statement is used to ensure that the file is properly closed after the reading is complete, even if an exception is raised.
Extract the Numbers Greater Than 5 From the String
In this step, you will learn how to extract the numbers greater than 5 from the string and concatenate them into a new string.
- Initialize an empty string to store the extracted numbers.
## Initialize an empty string to store the extracted numbers
numbers = ""
- Loop through each character in the string and check if it is a digit and greater than 5. If so, append it to the
numbersstring.
## Loop through each character in the string
for char in string:
## If the character is a digit and greater than 5
if char.isdigit() and int(char) > 5:
## Append it to the numbers string
numbers += char
The isdigit() method checks if the character is a digit, and the int(char) converts the character to an integer to check if it is greater than 5.
Print the Extracted Numbers
In this step, you will learn how to print the extracted numbers.
- Print the
numbersstring.
## Print out the numbers string
print(numbers)
The final FindDigits.py file should look like this:
## Open the String.txt file in the same directory and read the string
with open("String.txt", "r") as f:
string = f.read()
## Initialize an empty string to store the extracted numbers
numbers = ""
## Loop through each character in the string
for char in string:
## If the character is a digit and greater than 5
if char.isdigit() and int(char) > 5:
## Append it to the numbers string
numbers += char
## Print out the numbers string
print(numbers)
You have now completed the project. Run the FindDigits.py file to see the output.
$ python FindDigits.py
876
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



