🚀 Mastering Strings in Python I’ve started learning Python, and today I explored String Indexing & Slicing. It’s amazing how easily you can manipulate text with just a few lines of code 👇 🔹 String Indexing name = "satish" print(name) # satish print(name[0]) # s print(name[-5]) # t 🔹 String Slicing product = "Laptop pro 2024" print(product[-4:]) # 2024 🔹 More Examples text = "DataAnalysis" # Extracting first 4 characters print("First 4 letters:", text[0:4]) # Data # Extracting characters from middle print("Middle slice:", text[4:12]) # Analysis # Extract till end print("Till end:", text[4:]) # Analysis # Extract from beginning print("From start:", text[:4]) # Data # Extract last 5 characters print("Last 5 letters:", text[-5:]) # alysis # Skip characters print("Skip Text :", text[0:12:3]) # Daaie # Reverse string print("Reverse :", text[::-1]) # sisylanAataD
Mastering Python String Indexing & Slicing
More Relevant Posts
-
#StringOperations in #Python (Must-Know Basics for #DataScience) Working with text data is very common in #DataScience. That’s why understanding #Strings in #Python is an important foundation. #Mutable vs #Immutable - #Mutable → can be changed after assignment - #Immutable → cannot be changed once created In Python, #String is immutable, meaning you cannot directly modify a character inside it. #EscapeCharacters in Strings Escape characters help format text output. Common ones: #\n → moves to the next line #\t → adds a tab space #StringConcatenation (Joining Strings) There are multiple ways to combine strings: - Using #PlusOperator (+) Best for combining only a few strings - Using #.join() Best for combining multiple strings efficiently - Using #format() Useful for structured text formatting - Using #fstring Most readable and widely used in modern Python #Indexing in Strings Left to right indexing starts from 0 Right to left indexing starts from -1 This helps access specific characters easily. #Slicing in Strings Slicing is used to extract a portion of a string. It is very useful during #DataCleaning and text preprocessing. Useful #StringMethods Some commonly used methods: #upper() → converts to uppercase #lower() → converts to lowercase #strip() → removes extra spaces #count() → counts occurrences of a character/word Key Takeaway If you understand #StringOperations well, you can handle real-world text data more confidently in #Python. #Python #StringOperations #DataScience #DataAnalytics #ProgrammingBasics #DataCleaning #MachineLearning #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
Day 4 ..🤩 1️⃣ Dictionaries Dictionaries store data in key–value pairs, making data access fast and meaningful. -> Ex : python student = {"name": "Alex", "age": 22} 2️⃣ Nested Dictionaries Nested dictionaries allow you to store structured or hierarchical data by placing dictionaries inside other dictionaries. -> Ex : python students = {"student1": {"name": "Alex", "age": 22}} 3️⃣ range() Function The `range()` function generates a sequence of numbers ,commonly used in loops. -> Ex : python for i in range(5): print(i) 4️⃣ Slicing Slicing is used to **extract a portion of a sequence like a list or string. -> Ex : python numbers = [1, 2, 3, 4, 5] print(numbers[1:4])
To view or add a comment, sign in
-
Day 9: Mastering Type Casting in Python 🐍 Today I explored how Python handles type conversions, and it's more powerful than I initially thought! Type casting lets us convert data from one type to another, which is essential when working with user inputs, APIs, or databases. Key takeaways: Implicit vs Explicit Casting: Python automatically converts some types (like int to float), but we often need to explicitly cast data using functions like int(), str(), float(), and bool(). Real-world scenario: Converting user input (always a string) into integers for calculations, or formatting numbers as strings for display. Common pitfalls I learned to avoid: Not every string can be cast to an integer, and float to int conversion truncates decimals rather than rounding. Code snippet from today: python # User age input age = int(input("Enter your age: ")) # Converting for display price = 49.99 print(f"Price: ${str(price)}") # List to string items = ['apple', 'banana', 'cherry'] print(', '.join(items)) The journey continues! Each day brings new understanding of how Python handles data behind the scenes. #Python #FullStackDevelopment #CodingJourney #100DaysOfCode #LearningToCode #WebDevelopment
To view or add a comment, sign in
-
-
🔷 Python Strings as Arrays – Indexing & Length In Python, strings are like arrays of characters. Each character has a position called an index. Index always starts from 0. 🔹 1️⃣ Creating a String ▶ Example txt = "python programs" print(txt) ✔ Output: python programs 🔹 2️⃣ Accessing Characters (Indexing) We can access each character using its index number. ▶ Example print(txt[1]) print(txt[7]) ✔ Output: y p ➡ Index starts from 0, not 1. 🔹 3️⃣ Index Out of Range Error If we access an index that does not exist, Python gives an error. ▶ Example print(txt[15]) ❌ Output: IndexError: string index out of range ➡ Because the string length is smaller than 16. 🔹 4️⃣ Finding Length of a String We use len() to find the total number of characters. ▶ Example print(len(txt)) ✔ Output: 15 ➡ Spaces are also counted. 📌 Understanding indexing helps in slicing, searching, and data processing. #Python #PythonStrings #Indexing #LearningPython #CodingJourney #DataAnalytics
To view or add a comment, sign in
-
-
🚀 New Blog Published: Sets in Python — Removing Duplicates & Boosting Performance Duplicates and slow lookups are common problems when working with real-world data. In this post, I explain how Python sets help you: ✅ Remove duplicates effortlessly ⚡ Improve performance with faster lookups 🧹 Clean and compare data using set operations 📌 Write clearer, more expressive Python code If you work with data, backend systems, or analytics, mastering sets can simplify a lot of logic. Read the full blog on Medium👇 Innomatics Research Labs #Python #Programming #DataCleaning #SoftwareDevelopment #BackendDevelopment #PythonTips #LearnToCode #DataEngineering #TechWriting
To view or add a comment, sign in
-
🚀 What I Revised today in Python: 💡 Variable in python: a=12 12 will get stored into RAM and a will hold the address of 12. print(id(12)) hashtag#output: 4404716384 a=12 print(id(a)) hashtag#output: 4404716384 🤔 proof using id()-----> id tells the memory address a=12 b=a print(id(a)) print(id(b)) hashtag#output: 4404716384 4404716384 a and b have the same memory address. a and b refer to same memory address. # this clears that 12 is stored into RAM, a and b stores the address of RAM. 👍 Clean variable names in python? use clear, descriptive and readable variable names------your future self will thank you! ✅ Good practice: clear and readable user_age=23 total_price=43.33 is_logged_in=True ❌ Avoid: unclear x=25 tp=49.99 p=True 💡 Tip: 1. Use snake_case_name. e.g., user_name, item_count 2. Don't reuse variable names for different things.
To view or add a comment, sign in
-
-
❌ Memorizing Python file syntax didn’t help me ✅ Working with real files did So I continued learning Python using mini interview-focused projects. 🔹 Mini Project: File Word Counter What it does: ✔ Reads content from a text file ✔ Counts number of words ✔ Handles file access safely 💡 Why I built this: Because Python interviews often test: • file handling • string processing • real-world data reading Instead of assuming clean input, I focused on reading and processing file data properly. 📌 Real data → practical coding → interview-ready thinking Code below 👇 try: with open("sample.txt", "r") as file: text = file.read() words = text.split() print("Word count:", len(words)) except FileNotFoundError: print("File not found") #Python #FileHandling #InterviewPreparation #CodingPractice #LearningByDoing
To view or add a comment, sign in
-
🚀 Day 16/30 – Python OOPs Challenge 💡 Operator Overloading in Python We learned that polymorphism means: 👉 Same name 👉 Different behaviour Today we’ll see how Python allows operators to behave differently. This is called Operator Overloading. 🔹 What is Operator Overloading? In Python: - + adds numbers - + also joins strings Same operator → different behaviour. We can also define how operators work for our own classes. 🔹 Example: ``` class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def display(self): print(self.x, self.y) p1 = Point(2, 3) p2 = Point(4, 5) p3 = p1 + p2 # Using overloaded + operator p3.display() ``` 🔹 What happened here? - We defined __add__() method - Now + works for Point objects - Python calls __add__() automatically 📌 Key takeaway: Special methods like __add__() allow operator overloading. 👉 Day 17: Method Overloading concept in Python (coming tomorrow) 👍 Like | 💬 Comment | 🔁 Share 📍 Follow me to learn Python OOP step by step #Python #OOP #LearningInPublic #30DaysOfPython #CodingJourney
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