String Slicing and Methods (Part 2)
Continuing from our previous post on Python strings, let’s explore slicing and some powerful string methods.
4. Slicing Strings:
You can extract parts of a string using slicing. The syntax is string[start:end], where the slice includes the start index but excludes the end index.
Example:
5. String Methods:
Python offers a wide array of methods to manipulate strings. Let’s explore the most commonly used string methods.
5.1. .upper() and .lower()
Converts the entire string to uppercase or lowercase.
5.2. .strip(), .lstrip(), .rstrip()
Removes whitespace from both ends, left side, or right side of the string, respectively.
5.3. .replace(old, new)
Replaces all occurrences of the substring old with new.
5.4. .find(substring) and .index(substring)
Finds the first occurrence of the substring in the string. .find() returns -1 if the substring is not found, while .index() raises a ValueError.
5.5. .startswith(substring) and .endswith(substring)
Checks whether the string starts or ends with the specified substring.
5.6. .split(separator)
Splits the string into a list of substrings based on the specified separator. The default separator is any whitespace.
5.7. .join(iterable)
Joins elements of an iterable (like a list) into a string using the specified separator.
5.8. .capitalize() and .title()
5.9. .count(substring)
Returns the number of occurrences of the substring in the string
In the next post, we'll cover more methods, string formatting, and immutability in Python strings!
#PythonProgramming #CodeNewbie #WebDevelopment #CodingTips #PythonLearning #TechSkills #LearnToCode #DataScience #MachineLearning #FullStackDeveloper #ProgrammingCommunity #TechTips #WomenInTech #SoftwareEngineer #CodingLife #CodeWithMe