Mastering Python String Manipulation with Indexing, Slicing and Methods

🚀 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

To view or add a comment, sign in

Explore content categories