Python Top Codes
Python Code to Validate an Email Address
Many programs ask for an email address, like a sign up or a contact form. Before saving it, you should check that it looks like a real email. In Python this is easy with the re module (regular expressions).
Python function to validate an email
import re
pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
def is_valid_email(email):
return re.match(pattern, email) is not None
tests = [
"robin@example.com",
"robin@example",
"robin.kumar+test@mail.co.in",
"robin@@example.com",
"@example.com",
]
for email in tests:
print(email, "->", is_valid_email(email))
Output:
robin@example.com -> True
robin@example -> False
robin.kumar+test@mail.co.in -> True
robin@@example.com -> False
@example.com -> False
How the pattern works
| Part | Meaning |
|---|---|
^ and $ | Match the whole text, from the start to the end |
[A-Za-z0-9._%+-]+ | One or more letters, digits or these symbols before the @ |
@ | Exactly one @ sign |
[A-Za-z0-9.-]+ | The domain name, like example or mail.co |
\.[A-Za-z]{2,} | A dot and an ending of at least 2 letters, like .com or .in |
Related: Python Modules, Python Strings.
Python Code to Read and Write a CSV File
A CSV (comma separated values) file stores table data as plain text, one row per line. It can be opened in Excel, and Python has a built-in csv module to work with it.
Read a CSV file
Suppose we have a file named students.csv with this content:
name,marks
Robin,85
Maria,92
John,78
DictReader reads every row as a dictionary, using the first line as the keys.
import csv
total = 0
count = 0
with open("students.csv", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["marks"])
total += int(row["marks"])
count += 1
print("Average:", total / count)
Output:
Robin 85
Maria 92
John 78
Average: 85.0
Values from a CSV file are always strings, so we used int() for the marks.
Write a CSV file
import csv
rows = [
["name", "marks"],
["Robin", 85],
["Maria", 92],
]
with open("result.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
print("File saved")
Output:
File saved
The new file result.csv will have this content:
name,marks
Robin,85
Maria,92
Related: Python File Handling.
Python Code to Work with JSON Data
JSON is a text format used by websites and APIs to send data. It looks like a Python dictionary. Python has a built-in json module to convert between JSON text and Python objects.
JSON string to Python (json.loads)
import json
data = '{"name": "Robin", "age": 25, "skills": ["Python", "SQL"]}'
user = json.loads(data)
print(user["name"])
print(user["skills"][0])
print(type(user))
Output:
Robin
Python
<class 'dict'>
Python to JSON string (json.dumps)
import json
user = {"name": "Robin", "age": 25, "skills": ["Python", "SQL"]}
print(json.dumps(user))
Output:
{"name": "Robin", "age": 25, "skills": ["Python", "SQL"]}
Add indent=2 to json.dumps() to get a nicely formatted text with line breaks.
Save to and load from a file
import json
user = {"name": "Robin", "age": 25}
with open("user.json", "w") as f:
json.dump(user, f)
with open("user.json") as f:
loaded = json.load(f)
print(loaded["age"])
Output:
25
Related: Python Dictionary and Python File Handling.
Python Code to Count Word Frequency in Text
Counting how often each word appears is a common job, for example to find the most used words in an article. Python makes it short with collections.Counter.
Count words with Counter
from collections import Counter
text = "to be or not to be that is the question to be"
words = text.split()
counts = Counter(words)
print(counts)
print(counts.most_common(2))
print(counts["be"])
Output:
Counter({'to': 3, 'be': 3, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1})
[('to', 3), ('be', 3)]
3
The same without Counter
A normal dictionary also works. This is how Counter works inside.
text = "to be or not to be"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
Output:
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
Related: Python Dictionary and Python Strings.
Python Code to Flatten a Nested List
A nested list is a list that has other lists inside it. Flattening means making one simple list with all the values. The list can be nested to any depth, so a recursive function is the best way.
Python function to flatten a list
def flatten(items):
result = []
for item in items:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
nested = [1, [2, 3], [4, [5, 6]], 7]
print(flatten(nested))
Output:
[1, 2, 3, 4, 5, 6, 7]
How it works
- The function goes through each item of the list.
- If the item is also a list (
isinstance(item, list)), the function calls itself for it and adds the flat result withextend(). - Otherwise, the item is a plain value and is added with
append().
For a list that is only one level deep, a list comprehension is enough:
matrix = [[1, 2], [3, 4], [5]]
flat = [x for row in matrix for x in row]
print(flat)
Output:
[1, 2, 3, 4, 5]
Related: Python Lists and Python Functions (recursion).
Python Code to Generate a Random Password
A good password is long and random. In Python you can generate one with the secrets module, which is made for passwords and tokens.
Python function to generate a password
import secrets
import string
def generate_password(length=12):
chars = string.ascii_letters + string.digits + "!@#$%"
return "".join(secrets.choice(chars) for _ in range(length))
print(generate_password())
print(generate_password(16))
Sample output (the password is random, so yours will be different):
k9Fz@Tq2LmB8
Xw3#Pq9mZc7!Rv2d
How it works
string.ascii_lettershas all upper and lower case letters, andstring.digitshas 0 to 9.secrets.choice()picks one random character from the text.- The generator expression picks
lengthcharacters, and"".join()joins them into a string.
Related: Python Modules and Python Strings.