Small confession: I’ve never really liked Python’s .title(). It seems fine at first, but the more you use it, the more little issues show up. Acronyms get mangled, edge cases slip through, and your nicely formatted text starts looking slightly off. After running into this a few times, I ended up writing a version that behaves closer to what I expect: title_case = lambda s: re.sub( r"[A-Za-z]+(?:'[A-Za-z]+)?", lambda m: ( lambda w, b: w if re.fullmatch(r"[A-Z]+(\.[A-Z]+)*\.?", b) else w if not (b.islower() or b.isupper()) else w.capitalize() )(m.group(0), m.group(0).split("'")[0]), s ) It is simple, but it handles a few things better for my use cases: • Keeps acronyms like “NASA” and “U.S.A.” intact • Leaves mixed-case words as they are • Handles basic apostrophes more cleanly It is not perfect, but it works better for the cases I run into most often. It also made me realize that built-in functions are not always the best fit. Sometimes you need something slightly different for your own context. Curious to hear, what is a built-in function you have replaced or wrapped because it did not quite do what you needed? #Python #Programming #SoftwareDevelopment #Coding #DeveloperLife #AIWithAnishArya
Replacing Python's title() Function for Custom Needs
More Relevant Posts
-
🚀 Day 22 of My Generative & Agentic AI Journey! Today’s focus was on Comprehensions in Python — a concise and powerful way to create collections using a single line of code. Here’s what I learned: ⚡ Comprehensions in Python: • Used to create lists, sets, dictionaries, and even generators • Help write logic in a compact and readable way 🧠 Where are they used in real life? • Filtering items → Selecting specific elements from data • Transforming items → Modifying data while creating a new collection • Creating new collections → Generating lists, sets, or dictionaries efficiently • Flattening nested structures → Converting nested data into a single structure 🎯 Purpose of Comprehensions: • Cleaner code → Less lines, more readability • Faster execution → More optimized than traditional loops 💡 Key takeaway: Comprehensions make Python code more elegant and efficient — a must-know concept for writing professional-level code. Moving one step closer to writing optimized and clean Python 🚀 #Day22 #Python #GenerativeAI #AgenticAI #LearningJourney #BuildInPublic
To view or add a comment, sign in
-
🚀 Day 29 of My Generative & Agentic AI Journey! Today’s focus was on diving deeper into Object-Oriented Programming (OOP) in Python — understanding how objects behave with class properties. Here’s what I learned: 🎭 Attribute Shadowing: • Objects can override (shadow) class attributes by defining their own value • Once overridden, the object uses its own value instead of the class value 👉 Even if the class has a default value, each object can have its own version 🗑️ Deleting Attributes: • Attributes can be removed from an object • After deletion, Python falls back to the class attribute (if it exists) 👉 Helps understand how Python searches for values (object → class) 🧠 self Keyword: • self refers to the current instance of the class • Used to access and modify object-specific data inside methods 👉 Allows each object to maintain its own state 💡 Key takeaway: Understanding attribute shadowing and self helps in controlling how data is stored and accessed in objects — making OOP more powerful and flexible. Going deeper into Python’s object-oriented concepts 🚀 #Day29 #Python #OOP #GenerativeAI #AgenticAI #LearningJourney #BuildInPublic
To view or add a comment, sign in
-
Diving Deep into Python Magic Methods . Recently, I started exploring the internals of Python’s magic methods — those special methods that begin and end with double underscores (__). These aren’t typically called directly; instead, Python invokes them behind the scenes to enable powerful behaviors. These methods can be broadly categorized into: * Callable Objects → __call__() * Iterator Pattern → __init__(), __iter__(), __next__() * Finite Iterators * Context Managers ¥ Understanding the for Loop Internals A for loop in Python is actually built on the Iterator Protocol. Under the hood, it relies on three key magic methods: __init__() → initializes the object __iter__() → returns the iterator object (usually self) __next__() → returns the next value in the sequence ⚙️ How the for Loop Works Internally 1)iter(obj) is called automatically This invokes __iter__() and returns an iterator 2) next(obj) is called repeatedly This invokes __next__() and fetches values 3)Loop continues until StopIteration is raised Without it, the loop runs infinitely 🧠 Example: Custom Iterator class Repeat: def __init__(self, msg): self.msg = msg def __iter__(self): return self def __next__(self): return self.msg This will print the same message infinitely because StopIteration is never raised. Key Insight A for loop is essentially syntactic sugar over a while loop using the iterator protocol. Understanding this gives you deeper control over debugging and helps you identify the root cause of issues in iteration-heavy code. ✨ Once you understand what's happening behind the scenes, Python feels a lot less “magical” and a lot more predictable. For better understanding and clarity I suggest referring the image attached. Till then Happy Sunday, Happy learning and Happy growing. #Python #Programming #SoftwareDevelopment #Coding #PythonInternals #OOP #Developers #Learning #Tech #CSStudents #Debugging
To view or add a comment, sign in
-
-
🚀 Day 13 of Python Practice – Find Pairs with Given Sum Today’s problem is a classic interview favorite 👇 👉 Problem Statement: Given an array of integers and a target value, find all pairs whose sum equals the target. Example: Input: nums = [2, 4, 3, 5, 7], target = 7 Output: (2,5), (4,3) 💡 Approach 1: Brute Force (Nested Loop) ✔️ Simple but not efficient ✔️ Time Complexity: O(n²) nums = [2, 4, 3, 5, 7] target = 7 pairs = [] for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: pairs.append((nums[i], nums[j])) print(pairs) ⚡ Approach 2: Using Hash Set (Optimized) ✔️ Efficient lookup ✔️ Time Complexity: O(n) nums = [2, 4, 3, 5, 7] target = 7 seen = set() pairs = [] for num in nums: complement = target - num if complement in seen: pairs.append((complement, num)) seen.add(num) print(pairs) 🔥 Approach 3: Using Dictionary (Handles Frequency) ✔️ Useful when duplicates exist ✔️ Time Complexity: O(n) nums = [2, 4, 3, 5, 7] target = 7 freq = {} pairs = [] for num in nums: complement = target - num if complement in freq and freq[complement] > 0: pairs.append((complement, num)) freq[complement] -= 1 else: freq[num] = freq.get(num, 0) + 1 print(pairs) ✨ Key Takeaways: ✅ Brute force works but is slow ✅ Hashing improves performance significantly ✅ Always think about edge cases (duplicates, negative numbers) 📌 Pro Tip: This problem is a foundation for more advanced concepts like Two Sum, hashing, and sliding window techniques. 💬 How would you solve this differently? Drop your approach below! #Python #CodingChallenge #Day13 #ProblemSolving #DataStructures #Algorithms #LinkedInLearning #CodeDaily # 30days challenges
To view or add a comment, sign in
-
Friends, I’ve published an article on Medium about knime2py: Can LLMs help build code generators? A practical look at knime2py, KNIME-to-Python conversion.
To view or add a comment, sign in
-
I used to think Python was just about writing code. That changed when I started working with libraries. Once I got into NumPy, Pandas, and the rest, I realized it’s less about coding and more about solving problems with the right tools. Each library started to click in its own way: • Pandas → messy, real-world data that needs cleaning and shaping • NumPy → handling performance-heavy numerical operations • Matplotlib & Seaborn → actually understanding what the data is saying • Scikit-learn → taking it a step further with predictions But the biggest shift? Not just learning the libraries… 👉 Learning when to use which one That’s what made everything start to make sense. I’m still learning, but now I approach problems differently: Not “how do I code this?” But “what’s the right tool for this?” Curious - what’s the one Python library you use the most, and why? #Python #DataAnalytics #MachineLearning #Libraries
To view or add a comment, sign in
-
-
If Python feels inconsistent… you’re probably missing this. Day 15 — Polymorphism & Method Overloading Quick recap: Explored how the same method can behave differently based on context. Here’s what clicked: → Polymorphism isn’t theory — it’s flexibility in design One interface, multiple behaviors = cleaner, scalable code → Python doesn’t support traditional method overloading But it simulates it using default arguments & dynamic typing → Real power = writing code that adapts without rewriting logic The struggle? I kept trying to force Java-style overloading. Didn’t work. Breakthrough came when I stopped fighting Python… and started thinking in Pythonic design patterns. That shift changes everything. Showing up daily. No skips. No shortcuts. If you’re building real skills, consistency > intensity. What confused you the most about polymorphism? Or what should I break down next?
To view or add a comment, sign in
-
-
🚀 Day 84 – Strengthening Python Foundations 🐍 Today’s focus was on revisiting and revising the basics of Python, right up to comprehensions. Reinforcement of fundamentals is not just repetition — it’s about building clarity, confidence, and precision for advanced problem-solving. 🔹 Core Syntax Refreshed – Variables, operators, and expressions, ensuring fluency in the language’s building blocks. 🔹 Control Flow Mastery – Conditionals and loops revisited, sharpening logical thinking and structured problem-solving. 🔹 Functions & Scope – Re-examined how modular code works, reinforcing the importance of reusability and clarity. 🔹 Data Structures – Lists, tuples, sets, and dictionaries revised with practical examples, strengthening understanding of storage and retrieval. 🔹 Comprehensions – Explored list, set, and dictionary comprehensions, appreciating how they transform verbose loops into elegant, Pythonic one-liners. 🌱 Reflection – Revisiting basics is like polishing the foundation stones of a building. Each concept feels sharper, cleaner, and more intuitive, preparing me for deeper explorations in algorithms, problem-solving, and real-world applications. ⚡ Day 84 was about consolidation — turning knowledge into confidence, and confidence into readiness for the next leap forward. #Day84 #PythonLearning #CodingJourney #100DaysOfCode #LearnInPublic #10000Coders
To view or add a comment, sign in
-
🚀 Mastering Recursion with Gray Code Generation I recently worked on an interesting problem—generating Gray Codes using recursion in Python. This problem is a great example of how powerful and elegant recursive thinking can be. 🔹 What is Gray Code? Gray Code is a binary sequence where two consecutive values differ in only one bit. It has applications in digital systems, error correction, and algorithms. 🔹 Approach Used: Instead of generating all binary numbers and converting them, I used a recursive pattern: Base case: For n = 1 → ["0", "1"] Recursively get Gray codes for n-1 Prefix "0" to the original list Prefix "1" to the reversed list Combine both 🔹 Python Implementation: class Solution: def graycode(self,n): if n ==1: return ["0","1"] prev_gray = self.graycode(n - 1) result = [] for code in prev_gray: result.append("0" + code) for code in reversed(prev_gray): result.append("1" + code) return result 💡 Key Learning: Sometimes the best solutions don’t require complex logic—just recognizing patterns and applying recursion smartly. 📈 This problem strengthened my understanding of: Recursion Pattern building Problem decomposition Would love to hear how others approached this problem or optimized it further! 😊 #Python #Recursion #Algorithms #CodingJourney #DataStructures #ProblemSolving
To view or add a comment, sign in
-
Today's topic: recursion. A function that calls itself. Sounds simple, right? Here are two ways to add up a list of numbers: Without recursion — honest, reliable, easy to follow: python def suma(lista): suma = 0 for i in range(0, len(lista)): suma = suma + lista[i] return suma print(suma([6,3,4,2,10])) # 25 With recursion — elegant, almost poetic... and a little terrifying: python def suma(lista): if len(lista) == 1: return lista[0] else: return lista[0] + suma(lista[1:]) print(suma([6,3,4,2,10])) # 25 Same result. Two completely different roads to get there. The recursive version looks more "pro" — but if you forget to define when it stops, the function calls itself forever. Literally. Forever. 💀 So yes, it's getting challenging. And yes, recursion feels more elegant to write. But I'm not ready to fully trust something that could loop into oblivion if I blink wrong. Lesson of the day: simple is not the same as bad. And documenting the moments that confuse you? That's part of learning too. #Python #LearningToCode #DaysOfCode #PythonProgramming #CodingJourney #Recursion #BeginnerCoder #TechLearning #CodeNewbie #LinkedInLearning
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development