I used to think strings were the “easy” part of Python… today proved me wrong. 🐍 Day 04 of my #30DaysOfPython journey was all about strings, and honestly, this topic felt way more powerful than I expected. A string is basically any data written as text — and it can be written using single quotes, double quotes, or triple quotes. Triple quotes also make multiline strings super easy. Today I explored: 1. len() to check length 2. Concatenation to join strings together 3. Escape sequences like \\n, \\t, \\\\, \\', \\" 4. Old style formatting with %s, %d, %f 5. New style formatting with {} 6. Indexing and unpacking characters 7. Reversing a string with str[::-1] And then came the string methods… that part felt like unlocking a toolbox: capitalize(), count(), startswith(), endswith(), find(), rfind(), format(), index(), rindex(), isalnum(), isalpha(), isdigit(), isnumeric(), isidentifier(), islower(), isupper(), join(), strip(), replace(), split(), title(), swapcase() What hit me today was this: strings are everywhere. Names, messages, input from users, file data, logs, even the little things we ignore at first. So yeah — not “just text.” More like one of the most important building blocks in programming. Github Link - https://lnkd.in/gUkeREkz What was the first Python topic that looked simple but turned out to have way more depth than expected? #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
Unlocking String Power in Python
More Relevant Posts
-
Level Up Your Python API Design: Mastering / and * Have you ever looked at a Python function signature and wondered what those / and * symbols actually do? While many developers stick to standard arguments, modern Python (3.8+) provides surgical precision over how functions receive data. Understanding this is key to building robust, self-documenting APIs. Check out this "Ultimate Signature" example: def foo(pos1, pos2, /, pos_or_kwd1, pos_or_kwd2='default', *args, kwd_only1, kwd_only2='default', **kwargs): print( f"pos1={pos1}", f"pos2={pos2}", f"kwd_only1={kwd_only1}", # ... and so on ) The Breakdown: Positional-Only (/): Everything to the left of the slash must be passed by position. You cannot call foo(pos1=1). This is perfect for performance and keeping your API flexible for future parameter renaming. Positional-or-Keyword: The "classic" Python parameters that can be passed either way. The Collector (*args): Grabs any extra positional arguments and packs them into a tuple. Keyword-Only: Everything after *args (or a standalone *) must be named explicitly. This prevents "magic number" bugs and makes the intent of the caller crystal clear. The Dictionary (**kwargs): Catches any remaining keyword arguments. Why should you care? Good code isn't just about making it work; it’s about making it hard to use incorrectly. By using these boundaries, you create a strict contract. You force clarity where it’s needed (Keyword-Only) and allow flexibility where it’s not (Positional-Only). Are you using these constraints in your daily development, or do you prefer keeping signatures simple? Let’s discuss below! 👇 #Python #SoftwareEngineering #CleanCode #Backend #ProgrammingTips #Python3 #CodingLife
To view or add a comment, sign in
-
🧠 Python Concept: strip(), lstrip(), rstrip() Clean your strings like a pro 😎 ❌ Problem text = " Hello Python " print(text) 👉 Output: " Hello Python " 😵💫 (extra spaces) ❌ Traditional Way text = " Hello Python " text = text.replace(" ", "") print(text) 👉 Removes ALL spaces ❌ (not correct) ✅ Pythonic Way text = " Hello Python " print(text.strip()) # both sides print(text.lstrip()) # left only print(text.rstrip()) # right only 🧒 Simple Explanation Think of it like cleaning dust 🧹 ➡️ strip() → clean both sides ➡️ lstrip() → clean left ➡️ rstrip() → clean right 💡 Why This Matters ✔ Clean user input ✔ Avoid bugs in comparisons ✔ Very useful in real-world apps ✔ Cleaner string handling ⚡ Bonus Example text = "---Python---" print(text.strip("-")) 👉 Output: "Python" 🐍 Clean data, clean code 🐍 Small functions, big impact #Python #PythonTips #CleanCode #LearnPython #Programming #DeveloperLife #100DaysOfCode
To view or add a comment, sign in
-
-
There is something very powerful in Python that you can unlock by implementing just 2 methods. __𝙡𝙚𝙣__ __𝙜𝙚𝙩𝙞𝙩𝙚𝙢__ For example, if you implement this: 𝗰𝗹𝗮𝘀𝘀 𝗗𝗲𝗰𝗸: 𝗱𝗲𝗳 __𝗶𝗻𝗶𝘁__(𝘀𝗲𝗹𝗳, 𝗰𝗮𝗿𝗱𝘀): 𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀 = 𝗰𝗮𝗿𝗱𝘀 𝗱𝗲𝗳 __𝗹𝗲𝗻__(𝘀𝗲𝗹𝗳): 𝗿𝗲𝘁𝘂𝗿𝗻 𝗹𝗲𝗻(𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀) 𝗱𝗲𝗳 __𝗴𝗲𝘁𝗶𝘁𝗲𝗺__(𝘀𝗲𝗹𝗳, 𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻): 𝗿𝗲𝘁𝘂𝗿𝗻 𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀[𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻] Your object automatically supports: • 𝗹𝗲𝗻(𝘥𝘦𝘤𝘬) • 𝘥𝘦𝘤𝘬[0] • slicing → 𝘥𝘦𝘤𝘬[:3] • iteration → 𝗳𝗼𝗿 𝘤𝘢𝘳𝘥 𝗶𝗻 𝘥𝘦𝘤𝘬 • 𝗶𝗻 operator • 𝗿𝗮𝗻𝗱𝗼𝗺.𝗰𝗵𝗼𝗶𝗰𝗲(𝘥𝘦𝘤𝘬) • 𝘀𝗼𝗿𝘁𝗲𝗱(𝘥𝘦𝘤𝘬) You didn’t implement: • iteration • slicing • search • random selection Python gave you all of that. That takeaway is: If your object behaves like a sequence, Implement __𝗹𝗲𝗻__ + __𝗴𝗲𝘁𝗶𝘁𝗲𝗺__ and let Python do the rest. Don’t build features. Plug into the Data Model. #python #datamodel #dunder #magicmethods #__len__ #__getitem__
To view or add a comment, sign in
-
I think dictionaries might be the first Python topic that actually feels like organizing real life. 🐍 Day 08 of my #30DaysOfPython journey was all about dictionaries, and this one felt especially useful because it is basically how Python stores meaningful information. A dictionary is an unordered, mutable key-value data type. You use a key to reach a value — simple, but powerful. Today I explored: 1. Creating dictionaries with dict() built-in function and {} 2. Storing different kinds of values like strings, numbers, lists, tuples, sets, and even another dictionary 3. Checking length with len() 4. Accessing values using key name in [] or get() method 5. Adding and modifying key-value pairs 6. Checking whether a key exists using in operator 7. Removing items with pop(key), popitem() (removes the last item), and del 8. Converting dictionary items with items() which returns a dict_item object that contains key-value pairs as tuples 9. Clearing a dictionary with clear() 10. Copying with copy() and avoids mutation 11. Getting all keys with keys() and values with values(). These will return views - dict_keys() and dict_values() What stood out to me today was how dictionaries make data feel searchable instead of just stored. That key-value structure makes them one of the most practical tools in Python when working with real information. One more day, one more topic, one more step toward thinking in Python instead of just reading Python. When did dictionaries finally stop feeling confusing for you — or are they still one of those topics that need a second look? Github Link - https://lnkd.in/ewzDyNyw #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
🐍 Python List Operations – The Only Cheat Sheet You'll Need Master lists with these 25+ essential operations: 🔍 Accessing & Finding • list[i] → Get single item by index • list[start:end] → Get multiple items (slicing) • a, b, c = list → Unpack all items into variables • list.index(x) → Find position of first item with value x • x in list → Check if value x exists (True/False) 📊 Analyzing & Counting • len(list) → Total number of items • list.count(x) → Count how many times value x appears • max(list) / min(list) → Find highest/lowest values ✏️ Modifying Lists • list.append(x) → Add item x to the end • list.insert(i, x) → Insert item x at index i • list.extend(other_list) → Add items from another list • list[index] = new_value → Change item at specific index 🗑️ Removing Items • list.pop(i) → Remove and return item at index i (default last) • list.remove(x) → Remove first occurrence of value x • list.clear() → Remove all items 🔄 Sorting & Copying • list.sort() → Sort list in place (ascending) • list.reverse() → Flip order in place • new_list = sorted(list) → Get sorted copy • copy_list = list.copy() → Create a shallow copy ⚙️ Iteration & Processing • enumerate(list) → Iterate with index and value • [fn(x) for x in list if condition] → List comprehension (filter + transform in one line) • zip(list_a, list_b) → Pair items from two lists 💡 Pro tip: List comprehension is the most elegant Python feature. Master it and you'll write cleaner, faster code. #Python #PythonLists #CodingCheatSheet #DataStructures #LearnPython
To view or add a comment, sign in
-
-
Python: sort() vs sorted() Have you ever had to pause for a second and think: “Do I need sort() or sorted() here?” 😅 This is the common Python confusions. Let’s clear it up. 🔹 list.sort() ◾ A method (belongs to list objects) ◾ Works only on lists ◾ Sorts the list in-place ◾ Changes the original list ◾ Returns None Example: numbers = [3, 1, 4, 2] numbers.sort() print(numbers) # [1, 2, 3, 4] 🔹 sorted() ◾ A function (built-in Python function) ◾ Returns a new sorted list ◾ Does NOT change the original ◾ Works on any iterable Example: numbers = [3, 1, 4, 2] new_numbers = sorted(numbers) print(new_numbers) # [1, 2, 3, 4] print(numbers) # [3, 1, 4, 2] The key difference: sort() → changes your original data sorted() → keeps your original data safe 💡 Quick way to remember: 👉 If you want to keep the original, use sorted() 👉 If you want to modify the list directly, use sort() #Python #Programming #LearnPython #DataScience #LearningJourney #WomenInTech
To view or add a comment, sign in
-
-
Python has easy ways to make your text, numbers, and dates look clear and professional. Here are 4 tricks you should try: 1. f-Strings :The easiest way to put variables straight into your text. Fast, readable, perfect for quick outputs. name = "Mayar" age = 22 print(f"My name is {name} and I am {age} years old.") 2. Alignment & Width :Keep tables, reports, or lists neat by aligning text and numbers. Left, center, or right—your choice! print("{:<10} | {:^10} | {:>10}".format("Name", "Age", "Score")) print("{:<10} | {:^10} | {:>10}".format("Mayar", 22, 95)) 3. Template Strings :Create reusable text templates and fill in values later. Makes your code cleaner and easier to manage. from string import Template t = Template("Hello $name, your score is $score.") print(t.substitute(name="Mayar", score=95)) 4. Date & Time Formatting :Show dates and times in a clear, readable way. Useful for reports, logs, or messages. from datetime import datetime now = datetime.now() print(f"Date: {now:%d-%m-%Y} Time: {now:%H:%M:%S}") CodeAcademy_om Kulsoom Shoukat Ali Sultan AL-Yahyai #Python #Coding #PythonTips #Developer #LearnPython #TechSkills #CodeBetter #DateTime
To view or add a comment, sign in
-
-
🚀 Python GIL vs No-GIL — Real FastAPI Benchmarks (Python 3.13) Free-threaded Python is no longer just an experiment — it’s starting to show real impact. I came across a benchmark comparing Python 3.12 (with GIL) vs Python 3.13t (No-GIL) using FastAPI, and the results are pretty interesting 👇 💡 Key Takeaways: 🔹 Massive CPU Boost (~8x) CPU-bound endpoints jumped from ~4 RPS to ~32 RPS — with ZERO code changes. This is what true parallelism across cores looks like. 🔹 Threading inside requests ≠ better performance Even without GIL, spawning threads inside a single request didn’t help. Why? Under load, request-level parallelism already saturates the CPU. Extra threads just add overhead. 🔹 I/O performance unchanged No surprise here — GIL was never the bottleneck for I/O-bound workloads. Async + I/O still behaves the same. 📊 What this means in practice: ✅ Use No-GIL Python when: - You have CPU-heavy APIs (ML inference, image processing, data pipelines) - High concurrency + CPU contention exists - You previously relied on multiprocessing to bypass GIL ❌ Don’t expect gains if: - Your app is mostly I/O (DB calls, HTTP requests) - You’re already using async effectively ⚠️ Things to keep in mind: - Free-threading is still evolving - Thread safety is now YOUR responsibility - Some C extensions may not be ready yet 🔥 The most exciting part? Same code. Same FastAPI app. Just a different Python runtime → 8x improvement. This could seriously change how we design backend systems in Python. Curious — would you switch to No-GIL Python for your APIs? #Python #FastAPI #BackendEngineering #Performance #Concurrency #AI #SoftwareEngineering
To view or add a comment, sign in
-
-
🐍 The most misunderstood line in Python is this: for item in [1, 2, 3]: Most developers think the for loop just "goes through the list". What it actually does: calls iter([1,2,3]) to get an iterator, then calls next() on it repeatedly until StopIteration is raised. That's the entire protocol. Once you understand that, generators click immediately. A generator function with yield IS an iterator — Python implements iter and next automatically. And the magic of yield is that the function pauses at each yield and resumes from there on the next call. Full guide: iterator protocol from scratch, generator functions vs expressions, yield from for delegation, lazy 5-stage file processing pipeline, context managers (enter/exit), @contextmanager, suppress, ExitStack, and send()/throw() for two-way generator communication. A generator expression uses 200 bytes. An equivalent list uses 8MB. For the same data. 📎 Free PDF. Zero pip installs — pure Python standard library. #Python #Generators #Iterators #ContextManagers #PythonProgramming #SoftwareEngineering #CleanCode #BackendDev #Programming
To view or add a comment, sign in
-
Technical post: I've been posting some graphs on here, talking about functions and "equivalence". This was all started by working on porting an MLOPs framework from python 3.10 to 3.12, and all the "dependency hell" one has to go through. Then naturally the question arose "What are the boundaries of one project to another, in terms of functions being called etc.,?" This led me down the rabbit hole (not too deep) of what happens when I do something like python -m <module> <somescript>. Specifically, what is a "no op" module, and what kind of ops can we inject, thanks to python being an interpreted language. A few years ago I'd worked on something along similar lines called TracePath, which provided a decorator to do something similar (e.g. who called who, how long it took, etc.). So I merged these two ideas (avoid decorating every function, have an "inspector" module) and ran this on a simple pandas dataframe creation. The resulting function invocation graph is the image attached to this post. When I ran it across the whole workflow (create, load, transform data etc.,), the graph had ~9000 connections. The nice thing is I can specify which modules (e.g. only pandas, or pandas and numpy) should be added to the graph etc. What do you think is the next logical thing to do with something like this? What kind of graphs would well structured software produce? How about badly written software? #graphs #swe #dependencyhell #python
To view or add a comment, sign in
-
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