String Slicing and Methods (Part 2)

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:

Article content

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.

Article content

5.2. .strip(), .lstrip(), .rstrip()

Removes whitespace from both ends, left side, or right side of the string, respectively.

Article content

5.3. .replace(old, new)

Replaces all occurrences of the substring old with new.

Article content

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.

Article content

5.5. .startswith(substring) and .endswith(substring)

Checks whether the string starts or ends with the specified substring.

Article content

5.6. .split(separator)

Splits the string into a list of substrings based on the specified separator. The default separator is any whitespace.

Article content

5.7. .join(iterable)

Joins elements of an iterable (like a list) into a string using the specified separator.

Article content

5.8. .capitalize() and .title()

  • .capitalize() capitalizes the first character of the string.
  • .title() capitalizes the first letter of each word in the string.

Article content

5.9. .count(substring)

Returns the number of occurrences of the substring in the string

Article content

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

To view or add a comment, sign in

More articles by Prashant Patel

Insights from the community

Others also viewed

Explore topics