π Unlocking Python's Power: Mastering Everyday Coding Tasks!
π Let's dive into the realm of Python one-liners, where a single line of code packs a powerful punch! π₯ Here are some nifty tricks to streamline your coding tasks:
- Read Lines from a File: π Accessing file content effortlessly!
lines = [line.strip() for line in open('example.txt')]
- Count Lines in a File: π Keeping track of file length like a pro!
line_count = sum(1 for line in open('example.txt'))
- List Comprehension with Conditional: π Filtering lists with ease!
filtered_list = [x for x in my_list if x > 0]
- Calculate Average of a List: π Math made simple!
average = sum(my_list) / len(my_list) if len(my_list) > 0 else 0
- Conditional Value Assignment: π― Let Python make decisions for you!
result = x if condition else y
- Handle Zero Division Error: β οΈ Avoiding pitfalls gracefully!
result = numerator / denominator if denominator != 0 else 0
- Fetch HTML Content with Requests: π Bringing web data to your fingertips!
import requests; html_content = requests.get('https://example.com').text
- Multithreading with threading Module: π Boosting performance with parallelism!
import threading; threading.Thread(target=my_function).start()
- Hashing with hashlib: π Keeping passwords secure with hashing!
import hashlib; hashed_password = hashlib.sha256(password.encode()).hexdigest()
- Check if a key exists in a dictionary: ποΈ Navigating dictionaries like a seasoned explorer!
is_present = 'key' in {'key': 'value'}
- Removing duplicates from a list while preserving order: π Keeping things tidy without losing track!
unique_list = list(dict.fromkeys([1, 2, 2, 3, 4]))
- Download a file from a URL: π₯ Fetching files with finesse!
urllib.request.urlretrieve("https://lnkd.in/gsGhU6f7", "downloaded_file.zip")
- List files in a directory: π Exploring directories with Python's directory prowess!
files = [f for f in os.listdir("path/to/dir") if os.path.isfile(os.path.join("path/to/dir", f))]
Top comments (0)