🚀 Mastering Python String manipulation (Indexing, Slicing, and Methods): #### 1. String Indexing : Indexing allows you to access individual characters within a string based on their position. Python uses zero-based indexing, meaning the first character is at position 0. Positive Indexing : Starts from 0 at the beginning of the string and increases. Example: For the string "Madhav", index 0 is M, 1 is a, 2 is d, and so on. Negative Indexing : Starts from -1 at the very end of the string and decreases towards the beginning. Example: For "Madhav", index -1 is v, -2 is a, and so on. Syntax Example: variable[index] python name = "Madhav" print(name[0]) # Output: M print(name[-1]) # Output: v #### 2. String Slicing : Slicing allows you to extract a subset or a range of characters from a string. Syntax: string[start:end:step] start: The index to begin slicing (inclusive). end: The index to stop slicing (exclusive). step: The increment value (default is 1). Basic Slicing : python name = "Madhav" print(name[0:3]) # Output: Mad (Characters at 0, 1, 2) Reversing a String : Using a step of -1 to reverse the entire string. python print(name[::-1]) # Output: vahdaM #### 3. String Methods : These built-in functions allow for common string modifications covers commonly used built-in methods to modify or analyze strings 1. len(): Returns the total number of characters in a string, including spaces. Example: len('Hello World') returns 11. 2. upper() & lower(): Converts string case for normalization. Example: 'python'.upper() becomes 'PYTHON'. 3. strip(): Removes leading and trailing whitespace, crucial for data cleaning. Example: ' data '.strip() becomes data. 4. find(): Locates the index (position) of a specific character or substring. Example: 'linkedin'.find('k') returns 4. 5. replace(): Swaps old substrings with new ones. Example: 'Hello Rishabh'.replace('Rishabh', 'User') becomes 'Hello User'. 6. split(): Breaks a string into a list based on a delimiter, great for parsing text data. Example: 'apple,banana'.split(',') returns ['apple', 'banana']. 7. join(): Combines a list of strings into a single string using a specified separator. Example: ' - '.join(['A', 'B', 'C']) returns 'A - B - C'. #Python #DataScience #Coding #Learning #TechTips
Mastering Python String Manipulation with Indexing, Slicing and Methods
More Relevant Posts
-
✅ Week 2 of 180 — Python Lists are basically a Swiss Army knife! 🔪 Last session was Strings — fixed, immutable, locked. 🔒 Today? We unlocked something FAR more powerful. 🔓 Lists in Python — and honestly this changes EVERYTHING. 👇 🤔 So what IS a List? A List is an ordered, mutable collection of items that can hold multiple values — including different data types all in one place! fruits = ["apple", "banana", "cherry"] mixed = ["Alice", 30, True, 3.14] # yes, all in ONE list! 😲 ✅ 4 Key Properties: 📌 Ordered — every item has a fixed index position ✏️ Mutable — you can change, add or remove items freely 🔁 Allows Duplicates — same value can appear multiple times 🎲 Mixed Types — strings, ints, booleans all together! 📍 List Indexing — works exactly like Strings! nums = [10, 20, 30, 40, 50] # 0 1 2 3 4 ← positive index # -5 -4 -3 -2 -1 ← negative index print(nums[0]) # 10 → first item print(nums[-1]) # 50 → last item If you understood String indexing last session — congrats, you already know List indexing! 😄 ✂️ List Slicing — same syntax as Strings! nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] → index 1 to 3 print(nums[::-1]) # [50, 40, 30, 20, 10] → REVERSED! 🔄 Python really said: "Learn it once, use it everywhere." 😂 🛠️ List Methods — the full toolkit: fruits = ["apple", "banana", "cherry"] fruits.append("kiwi") # adds to END fruits.insert(1, "mango") # inserts at index 1 fruits.remove("banana") # removes first occurrence fruits.pop(2) # removes & returns at index 2 fruits.sort() # sorts ascending fruits.reverse() # reverses the list fruits.clear() # removes ALL items new = fruits.copy() # creates a copy 🔥 The BIG difference from Strings: Strings → IMMUTABLE → methods return a NEW string Lists → MUTABLE → methods change the original list directly! # Strings - must reassign s = "hello" s = s.upper() # must save it back ✅ # Lists - changes happen in place! fruits.append("kiwi") # original list is updated automatically ✅ This tripped me up at first. Now it makes total sense! 😄 💡 Week 2 Summary so far: → Strings = read-only text with powerful methods 📖 → Lists = flexible, editable collections of anything 🗂️ Both use the same indexing and slicing — Python is beautifully consistent! 🐍 📅 Week 2 / 180 — Lists: DONE! ✅ Still going strong on my 6-Month GenAI & Agentic AI Certificate Program 🏛️ IIT Patna Certified print("Lists understood. Building momentum! 🚀") 💪 💬 Which List method do you use the most in your projects? Drop it below! 👇 ♻️ Repost if this helped you understand Python Lists better! #Python 🐍 #Lists #ListMethods #Week2 #GenAI 🤖 #IITPatna 🏛️ #LearningInPublic #100DaysOfCode #PythonBasics #DataStructures #CodingJourney #AgenticAI #NeverStopLearning 🚀 #BuildInPublic #AIForDevelopers
To view or add a comment, sign in
-
-
Making Python Interactive – Input, Strings & Indexing! ⌨️🔤 Programs get really powerful when they can talk back and forth with users. This session introduced me to taking input, manipulating strings, and accessing individual characters—skills that make coding dynamic and interactive! Here's what I learned: --- ➕ String Concatenation – Adding Strings Together Just like numbers, strings can be "added"—but instead of math, they get joined together. ```python a = "1" + "2" print(a) # Output: "12" (not 3!) ``` ✅ This is called String Concatenation Real example: ```python username = "Ravi" print("Hi " + username) # Output: Hi Ravi ``` --- ⚠️ Important: Can't Mix Types! ```python print("*" + 10) # ERROR! ``` ❌ TypeError: can only concatenate str (not "int") to str You can only add string to string—numbers need conversion or different approach. --- 🔁 String Repetition – Multiply Strings! Want 10 stars? Just multiply the string: ```python print("*" * 10) # Output: ********** ``` ✅ Called String Repetition Cool example: ```python s = "Python" s = ("*" * 3) + s + ("*" * 3) print(s) # Output: ***Python*** ``` --- 📏 Length of String – len() ```python username = "Ravi" length = len(username) print(length) # Output: 4 ``` len() counts all characters, including spaces and special chars. --- ⌨️ Taking User Input – input() Instead of hardcoding values, let the user type! ```python username = input() # User types something print("Hello " + username) ``` ✅ input() always returns a string Multiple inputs: ```python name = input() age = input() print(name + " is " + age + " years old") ``` Input: ``` Ravi 10 ``` Output: Ravi is 10 years old --- 🔢 String Indexing – Accessing Characters Strings are like sequences—each character has a position number (index) starting from 0. ``` String: R a v i Index: 0 1 2 3 ``` ```python username = "Ravi" print(username[0]) # Output: R print(username[1]) # Output: a print(username[2]) # Output: v print(username[3]) # Output: i ``` ✅ Index = position - 1 (first character is at 0) --- ✅ Key Takeaways: Concept Syntax Example String Concatenation str + str "Hi " + "Ravi" String Repetition str * number "*" * 10 String Length len(str) len("Ravi") User Input input() name = input() String Indexing str[index] name[0] --- 💬 Let's Discuss: What's the first interactive program you ever wrote? A greeting? A calculator? Or something more creative? Share your memories below! 👇 --- 🔖 #Python #CodingBasics #LearnToCode #StringManipulation #UserInput #ProgrammingForBeginners #NXTWave #TechJourney
To view or add a comment, sign in
-
Last week I shared a simple causal inference agent I built where Claude is the brain and Python is the hands (https://lnkd.in/gAUxCj8c). This week I want to pull back the curtain on how it actually works because understanding the architecture changed how I think about when agents are worth building at all. --- The agent has 3 layers: Layer 1: Tool Definitions Claude never sees your Python code. It sees JSON descriptions of what tools exist. Based on those descriptions + the data, it decides which tool to call and what arguments to pass. That's it. Layer 2: The Dispatcher When Claude says "call run_did," the dispatcher translates that into an actual Python function call. It also manages state — storing results, tracking where we are in the analysis, handling errors. Layer 3: Python Tools Each tool is a standalone module doing real statistical work — A/B test, DiD, Synthetic Control, report generation. Claude reasons about them. Python executes them. --- The benefits I'm seeing so far: · Clean separation — Claude handles reasoning, Python handles computation · Easily extensible — adding a new method is just adding a new tool · Auditable — every decision is logged and traceable · Testable — each tool works independently of the agent and can be changed/tested --- The biggest thing I'm still working through is identifying when an agent actually beats just writing a Python script? Current answer: Use a script when you already know which method to run. Use an agent when the right method depends on results you haven't seen yet – at the very least it can help reason a proper method that you can then explore. I'm genuinely still learning here, and the questions being asked of the agent are super basic and somewhat black and white. But one thing I'm fairly convinced of is that if you want consistent, reliable behavior from an agent, you need to give it structure — clear tool definitions, explicit guidelines in the system prompt, well-defined fallback logic. Without that, you're just asking a general LLM to figure it out, which is a bit scary and weaker in my opinion. Curious if others have found this to be true — or where you'd push back. #MarketingAnalytics #CausalInference #AgenticAI #DataScience #BuildingInPublic
To view or add a comment, sign in
-
-
🔥 Part-1: Tuples in Python (Complete Guide) 🔥 Tuples are one of the most important data structures in Python — simple, fast, and immutable! Let’s break it down in an easy and practical way 👇 📌 What is a Tuple? 👉 An ordered, immutable collection 👉 Allows duplicate values 👉 Written using parentheses () Example: fruits = ("apple", "orange", "cherry", "apple") print(fruits) # Output: ('apple', 'orange', 'cherry', 'apple') ✨ Ways to Create Tuples 🔹 1. Using Parentheses fruits = ("apple", "orange", "cherry") 🔹 2. Without Parentheses (Tuple Packing) numbers = 1, 2, 3, 4 print(type(numbers)) # Output: <class 'tuple'> 🔹 3. Single Element Tuple (Important ⚠️) single_tuple = ("apple",) print(type(single_tuple)) # Output: <class 'tuple'> 👉 Without comma, it becomes a string! 🎯 Accessing Elements 🔹 Indexing colors = ("red", "green", "blue", "orange") print(colors[0]) # red print(colors[-1]) # orange 🔹 Slicing nums = (10, 20, 30, 40, 50) print(nums[1:4]) # (20, 30, 40) ⚙️ Tuple Operations 🔹 Concatenation (+) print((1, 2) + (3, 4)) # (1, 2, 3, 4) 🔹 Repetition (*) print(("apple",) * 3) # ('apple', 'apple', 'apple') 🔁 Iteration in Tuple 🔹 Using for loop colors = ("red", "green", "blue") for color in colors: print(color) 🔹 Using while loop fruits = ("apple", "mango", "cherry") i = 0 while i < len(fruits): print(fruits[i]) i += 1 🛠️ Useful Methods & Functions 🔹 count() nums = (1, 2, 3, 2, 2) print(nums.count(2)) # 3 🔹 index() colors = ("red", "green", "blue") print(colors.index("green")) # 1 🔹 sorted() (returns list) nums = (3, 1, 2) print(sorted(nums)) # [1, 2, 3] 🔹 Built-in Functions numbers = (10, 20, 30, 40) print(len(numbers)) # 4 print(sum(numbers)) # 100 print(min(numbers)) # 10 print(max(numbers)) # 40 🎁 Packing & Unpacking 🔹 Unpacking coordinates = (10, 20, 30) x, y, z = coordinates print(y) # 20 🔹 Packing a = "Madhav" b = 21 c = "Engineer" tuple_pack = (a, b, c) print(tuple_pack) # ('Madhav', 21, 'Engineer') 🚀 Key Takeaways ✔ Tuples are immutable (cannot change) ✔ Faster than lists ✔ Useful for fixed data & security ✔ Supports indexing, slicing & iteration 💬 Stay tuned for Part-2 (Advanced Tuple Concepts) #Python #PythonProgramming #DataStructures #CodingTutorial #DataScience #SoftwareDevelopment
To view or add a comment, sign in
-
Day 23: Comprehensions — The "Pythonic" Way to Code ⚡ A Comprehension is a shorthand way to create a new collection (List, Dictionary, or Set) based on an existing one. It combines a for loop and an if statement into a single line. 1. List Comprehensions: The Standard Instead of creating an empty list and using .append(), you define the list's content in place. ❌ The Rookie Way: squares = [] for x in range(10): squares.append(x * x) ✅ The Pythonic Way: squares = [x * x for x in range(10)] 💡 The Engineering Lens: Comprehensions are actually slightly faster than for loops because they run at "C speed" inside the Python interpreter. However, if your comprehension is longer than one line, it’s better to use a regular loop for readability. 2. Adding Logic: The "if" Filter You can filter data while you build the list. Example: Create a list of even numbers only. evens = [n for n in range(20) if n % 2 == 0] 3. Dictionary Comprehensions You can build a key-value map just as easily. Example: Mapping names to their lengths. names = ["Alice", "Bob", "Charlie"] name_lengths = {name: len(name) for name in names} # Result: {'Alice': 5, 'Bob': 3, 'Charlie': 7} 4. Set Comprehensions Exactly like list comprehensions, but using {} to ensure all items are unique. Example: Getting unique file extensions from a list of files. files = ["test.py", "main.py", "data.csv", "script.py"] extensions = {f.split(".")[-1] for f in files} # Result: {'py', 'csv'} 💡 The "Clean Code" Rule of Thumb: Just because you can do it in one line doesn't mean you should. Do use it for: Simple transformations and filtering. Don't use it for: Complex logic with multiple if/else statements or "Nested Comprehensions" (a loop inside a loop). If another engineer has to read it three times to understand it, use a standard for loop instead. #Python #SoftwareEngineering #CleanCode #Pythonic #ProgrammingTips #LearnToCode #TechCommunity #DataScience #CodingEfficiency
To view or add a comment, sign in
-
⚡ I reduced 10 lines of Python code to just 1 line today. ❎Not using AI. ❎Not using complex libraries. ✅Just Python functions + map() + lambda(). And it reminded me how powerful clean logic can be. 🐍 1️⃣ Functions – The core building blocks of Python Functions help us organize logic and reuse code. Example: def square(num): return num * num Instead of repeating calculations, we simply call the function whenever needed. ✔ Cleaner code ✔ Reusable logic ✔ Easier debugging ⚡ 2️⃣ Lambda Functions – Quick one-line functions Sometimes we don’t need a full function definition. Python allows lambda functions for short operations. Example: square = lambda x: x*x print(square(5)) Output → 25 🔄 3️⃣ map() – Apply a function to an entire list Instead of writing loops, we can transform lists instantly. Example: numbers = [1,2,3,4] squares = list(map(lambda x: x*x, numbers)) print(squares) Output → [1,4,9,16] This makes data processing fast and elegant. 🧠 4️⃣ Small logic exercises that build real coding skills ✔ Check if a number is positive def check_number(n): Example: if n > 0: return "Positive" elif n == 0: return "Zero" else: return "Negative" ✔ Find the longest word in a list Example: words = ["python","data","programming","AI"] longest = max(words, key=len) print(longest) Output → programming ✔ Get unique sorted numbers numbers = [5,2,7,2,5,9] unique_sorted = sorted(set(numbers)) print(unique_sorted) Output → [2,5,7,9] 💡 Key takeaway Learning Python isn’t about memorizing syntax. It’s about thinking in logic blocks: • Functions • Lambda • map() • Smart data handling Master these… and Python becomes 10× more powerful. 💬 Let’s discuss Which Python concept helped you the most when learning? 1️⃣ Functions 2️⃣ Lambda 3️⃣ map() 4️⃣ Data logic Drop your answer in the comments 👇 #Python #PythonLearning #Coding #Programming #LearnToCode #PythonFunctions #Lambda #TechLearning
To view or add a comment, sign in
-
🚀 Day 26/30 📝List with Examples #30DaysOfPython Today I practiced important Python List Operations such as reverse(), copy(), and membership operators ("in", "not in"). I also experimented with multiple list methods together in one example to better understand how lists behave when we manipulate data. Lists are one of the most powerful and commonly used data structures in Python. 📌 reverse() "reverse()" is used to reverse the order of elements in a list. numbers = [10, 20, 30, 40, 50] numbers.reverse() print(numbers) Output: [50, 40, 30, 20, 10] ---------------------------------------------------------------------- 📌 copy() "copy()" creates a new list with the same elements as the original list. numbers = [10, 20, 30] new_list = numbers.copy() print(new_list) Output: [10, 20, 30] ---------------------------------------------------------------------- 📌 Membership Operators Membership operators check whether an element exists in a list. ✔ "in" → returns True if element exists ✔ "not in" → returns True if element does not exist numbers = [1, 2, 3, 4, 5] print(3 in numbers) print(10 not in numbers) Output: True True ---------------------------------------------------------------------- 🚀 Complete Example Using Multiple List Methods # Original list l = [10, 20, 30, 40] # insert element l.insert(2, 25) # extend list l.extend([50, 60]) # remove element l.remove(20) # pop element x = l.pop() # copy list new_list = l.copy() # reverse list l.reverse() # sort list new_list.sort() print("Original list after operations:", l) print("Sorted copied list:", new_list) # membership operators print(25 in l) print(100 not in l) Example Output: Original list after operations: [50, 40, 30, 25, 10] Sorted copied list: [10, 25, 30, 40, 50] True True ---------------------------------------------------------------------- 📚 What I Learned Today ✔ Using different Python list methods ✔ Reversing and copying lists ✔ Checking elements using membership operators ✔ Combining multiple list operations in one program ✔ Strengthening understanding of Python data structures ---------------------------------------------------------------------- 💡 Key Takeaway Learning and practicing list methods together in one program helps build stronger programming logic and improves the ability to manipulate data efficiently. Step by step improving my Python fundamentals 🚀 #Python #30DaysOfPython #PythonLists #CodingJourney #LearningPython #ProgrammingBasics #LearningDaily
To view or add a comment, sign in
-
-
Python Prototypes vs. Production Systems: Lessons in Logic Rigor 🛠️ This week, I stopped trying to write code that "just works" and started writing code that refuses to crash. As an aspiring Data Scientist, I’m learning that stakeholders don’t just care about the output—they care about uptime. If a single "typo" from a user kills your entire analytics pipeline, your system isn't ready for the real world. Here are the 4 "Industry Veteran" shifts I made to my latest Python project: 1. EAFP over LBYL (Stop "Looking Before You Leap") In Python, we often use if statements to check every possible error (Look Before You Leap). But a "Senior" approach often favors EAFP (Easier to Ask for Forgiveness than Permission) using try/except blocks. Why? if statements become "spaghetti" when checking for types, ranges, and existence all at once. Rigor: A try block handles the "ABC" input in a float field immediately, keeping the logic clean and the performance high. 2. The .get() Method: Killing the KeyError Directly indexing a dictionary with prices[item] is a ticking time bomb. If the key is missing, the program dies. The Fix: I’ve switched to .get(item, 0.0). This allows for a "Default Value" fallback in a single line, preventing "Dictionary Sparsity" from breaking my calculations. 3. Preventing the "System Crush" Stakeholders hate downtime. I implemented a while True loop combined with try/except for all user inputs. The Goal: The program should never end unless the user explicitly chooses to "Quit." Every "bad" input now triggers a helpful re-prompt instead of a system failure. 4. Precision in Data Type Conversion Logic errors often hide in the "Conversion Chain." I focused on the transition from String (from input()) to Int (for indexing). The Off-by-One Risk: Users think in "1-based" counting, but Python is "0-based." I’ve made it a rule to always subtract 1 from the integer input immediately to ensure the correct data point is retrieved every time. The Lesson: Coding is about the architecture of the "Why" just as much as the syntax of the "What." [https://lnkd.in/gvtiAKUb] #Python #DataScience #CodingJourney #CleanCode #BuildInPublic #SoftwareEngineering #SeniorDataScientist #TechMentor
To view or add a comment, sign in
-
-
Page-2 💡 Mastering Loops in Python: A Key Concept for Data Analysts! 📊 3. Loop Control Statements: These statements alter the normal flow of a loop. #### A. break Statement Terminates the loop entirely when a specific condition is met. python for i in range(5): if i == 3: break print(i) Output: 0, 1, 2 Explanation: The loop iterates from 0 to 9. When i reaches 3, the break statement is executed, stopping the loop immediately. Even though the range goes up to 10, the program exits the loop at 3. #### B. continue Statement Skips the current iteration and moves to the next one. python for i in range(5): if i == 3: continue print(i) Output: 0, 1, 2, 4 (Note: 3 is skipped) Explanation: The loop prints numbers from 0 to 4. When i is 3, the continue statement skips the print(i) line for that specific number, but the loop continues for 4. #### C. pass Statement A placeholder that does nothing. Used when a statement is required syntactically, but no action is needed. or a placeholder that does nothing, used to avoid syntax errors. python for i in range(3): pass # To be implemented later ### 4. Handling Infinite Loops The video demonstrates a practical example of combining a while True: loop (which runs forever) with a break statement to exit based on user input. Example: python while True: user_input = input("Enter exit to stop: ") if user_input == exit: print("Congrats! You guessed it right.") break else: print(f"Sorry, you entered {user_input}") Output Example: Enter 'exit' to stop: hello Sorry, you entered hello Enter 'exit' to stop: exit Congrats! You guessed it right. Explanation: The program continuously prompts the user for input. If the user types anything other than exit, it repeats. If the user types exit, the break statement terminates the loop, ending the program. ### 💡 Chapter Important Notes Python Loops allow for efficient automation of repetitive tasks. Use while loops when the number of iterations is unknown, but a condition must be met. Use for loops when iterating over a known sequence or a specific range. Control statements like `break` and `continue` give fine-grained control over loop execution. Crucial Note: Always ensure your while loop condition eventually becomes False to avoid infinite loops. #Python #Programming #Learning #DataScience #Coding #PythonTutorial
To view or add a comment, sign in
-
📘 Python for PySpark Series – Day 15 🎭 Polymorphism in Python ✨ What is Polymorphism? Polymorphism means “many forms”. It allows the same method or function to behave differently based on the object. ➡️ Promotes flexibility and dynamic behavior in code 🔹 Why Polymorphism? ✔ Improves code flexibility ✔ Reduces complexity ✔ Enhances readability ✔ Supports method reusability 🔹 Types of Polymorphism ✔ Method Overriding (Runtime) ✔ Method Overloading (Compile-time – limited in Python) ✔ Operator Overloading 🔹 Syntax (Method Overriding) class Parent: def show(self): print("Parent method") class Child(Parent): def show(self): print("Child method") 🔹 Example class Animal: def sound(self): print("Some sound") class Dog(Animal): def sound(self): print("Bark") class Cat(Animal): def sound(self): print("Meow") animals = [Dog(), Cat()] for a in animals: a.sound() ➡️ Same method sound() → different outputs 🔗 Why Polymorphism in PySpark? ✔ Same operations work on different data types (RDD, DataFrame) ✔ Functions behave differently based on input ✔ Helps in writing generic and reusable code 🏫 Real-Life Analogy (Remote Control 📺) One remote → multiple devices ➡️ Same button (action) → different behavior (TV, AC, etc.) 🧠 Interview Key Points ✔ Polymorphism = one interface, multiple implementations ✔ Achieved using method overriding ✔ Supports dynamic method dispatch ✔ Increases flexibility and scalability 🧠 Key Takeaway Polymorphism allows writing flexible and reusable code where the same operation behaves differently for different objects. 🔖 Hashtags #python #pyspark #dataengineering #oop #polymorphism #pythonbasics #learningjourney #coding
To view or add a comment, sign in
-
Explore related topics
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