Python From Beginner to Advanced

0% completed

Previous
Next
Python - String Methods

String methods in Python provide powerful tools for performing transformations and queries on string data. These methods can simplify tasks related to case conversion, alignment, splitting and joining, checking conditions (Boolean methods), finding and replacing substrings, and translating characters.

Understanding these methods is essential for efficient string manipulation and can significantly enhance text processing capabilities within Python applications.

Case Conversion Methods

Case conversion methods are used to change the text format between uppercase and lowercase. These methods do not modify the original string but return new strings with the changes applied.

MethodDescriptionTime Complexity
upper()Converts all lowercase letters in the string to uppercase.O(n)
lower()Converts all uppercase letters to lowercase.O(n)
capitalize()Capitalizes the first letter of the string and makes other letters lowercase.O(n)
title()Converts the first letter of each word to uppercase and the rest to lowercase.O(n)
swapcase()Swaps the case of each letter in the string.O(n)

Example - Using upper() and lower()

Python3
Python3

. . . .

Explanation:

  • text.upper() converts all characters in text to uppercase.
  • text.lower() converts all characters in text to lowercase.

Alignment Methods

Alignment methods help in formatting text by aligning it within a specified width.

MethodDescription
center(width)Centers the string within the specified width.
ljust(width)Left-justifies the string in the specified width.
rjust(width)Right-justifies the string in the specified width.

Example - Using center()

Python3
Python3

. . . .

Explanation:

  • title.center(20, '-') centers the string title within a total width of 20 characters, padding it with hyphens on both sides.

Split and Join Methods

Splitting and joining methods in Python are crucial for manipulating strings based on specific delimiters or conditions. These methods allow you to break a string into substrings, remove spaces, or combine multiple strings efficiently. Understanding these functions is essential for tasks such as data cleaning, parsing, and preparing text for further processing.

Here is a detailed table of the split and join methods provided by Python, each with a concise description:

MethodDescription
lstrip()Removes all leading whitespaces from the string.
rstrip()Removes all trailing whitespaces from the string.
strip()Removes both leading and trailing whitespaces from the string.
rsplit()Splits the string from the right at the specified separator and returns a list of substrings.
split()Splits the string according to the specified delimiter (defaults to any whitespace) and returns a list of substrings.
splitlines()Splits the string at newline characters (\n) and returns a list of lines, without newlines.
partition()Splits the string into a tuple of three elements around the first occurrence of the specified separator: the part before the separator, the separator itself, and the part after.
rpartition()Splits the string into a tuple of three elements around the last occurrence of the specified separator: the part before the separator, the separator itself, and the part after.
join()Joins the elements of an iterable into a single string, separated by the string on which join() is called.
removeprefix()Returns a string with the specified prefix removed, if present.
removesuffix()Returns a string with the specified suffix removed, if present.

Example - Demonstrating split(), rsplit(), and join()

In this example, we will use split(), rsplit(), and join() methods to illustrate how to split a string into substrings and then rejoin them into a single string.

Python3
Python3

. . . .

Explanation:

  • text.split(): This method splits text at each whitespace (the default delimiter) into a list of words.
  • text.rsplit(' ', 1): This method splits text from the right at spaces, but only does so once (maxsplit=1), which splits the string into two parts at the last space.
  • " ".join(words): This takes the list words and concatenates its elements into a single string, with each element separated by a space. This method reverses the splitting action, effectively rejoining the split words.

Python - Boolean String Methods

Boolean string methods in Python provide a way to check for specific properties of strings. These methods are useful for validating the contents of strings before processing them in your applications, such as ensuring that a string contains only certain types of characters (digits, alphanumeric, etc.) or conforms to a specific format. These methods return True or False depending on whether the string meets the condition specified by the method.

Here is a detailed table of the Boolean string methods available in Python, each with a description:

MethodDescription
isalnum()Returns True if all characters in the string are alphanumeric (letters and numbers only).
isalpha()Returns True if all characters in the string are alphabetic.
isdigit()Returns True if all characters in the string are digits.
isdecimal()Returns True if all characters in the string are decimal characters.
isnumeric()Returns True if all characters in the string are numeric characters.
islower()Returns True if all cased characters in the string are lowercase and there is at least one cased character.
isupper()Returns True if all cased characters in the string are uppercase and there is at least one cased character.
istitle()Returns True if the string is a titlecased string and there is at least one character, i.e., uppercase characters may only follow uncased characters and lowercase characters only cased ones.
isspace()Returns True if there are only whitespace characters in the string and there is at least one character.
isidentifier()Returns True if the string is a valid identifier according to Python’s language definitions.
isprintable()Returns True if all characters in the string are printable or the string is empty.
endswith(suffix)Returns True if the string ends with the specified suffix, otherwise False.
startswith(prefix)Returns True if the string starts with the specified prefix, otherwise False.

Example - Demonstrating Boolean Methods

To demonstrate some of these Boolean methods, we'll use a few examples:

Python3
Python3

. . . .

Explanation:

  • text.isalnum(): Checks if text contains only alphanumeric characters (letters and digits), which is true for "Hello123".
  • text.isalpha(): Verifies whether all characters in text are alphabetic, which is false since "Hello123" includes digits.
  • numeric_text.isdigit(): Returns True as "123456" consists solely of digits.
  • formatted_text.istitle(): Confirms that "Python Programming" follows title case formatting—first letters of each word are capitalized.
  • formatted_text.startswith("Python") and formatted_text.endswith("Programming"): These methods validate that the string starts with "Python" and ends with "Programming", respectively.

Python - Find and Replace Methods

The find and replace methods in Python are essential for text processing, allowing you to search for substrings within a string and modify content based on specific criteria. These methods can help locate positions, count occurrences, check for substring presence, and replace portions of the string conditionally.

Here is a detailed table summarizing the find and replace methods in Python, along with their descriptions:

MethodDescription
count(sub, beg, end)Counts how many times a substring sub occurs in the string or in a specified substring.
find(sub, beg, end)Searches for the substring sub within the string or a specified substring and returns the index of the first occurrence, or -1 if not found.
index(sub, beg, end)Similar to find(), but raises a ValueError if the substring sub is not found.
replace(old, new, max)Replaces occurrences of a substring old with new, replacing all occurrences unless max is specified.
rfind(sub, beg, end)Searches for the substring sub from the end of the string or a specified substring and returns the index of the last occurrence, or -1 if not found.
rindex(sub, beg, end)Similar to rfind(), but raises a ValueError if the substring sub is not found.
startswith(sub, beg, end)Checks if the string or a specified substring starts with the substring sub and returns True or False.
endswith(suffix, beg, end)Checks if the string or a specified substring ends with the suffix suffix and returns True or False.

Example - Demonstrating Find and Replace Methods

To illustrate some of these methods, we will use a practical example:

Python3
Python3

. . . .

Explanation:

  • text.count('hello'): Counts how many times "hello" appears in text.
  • text.find('hello'): Finds the first occurrence of "hello" in text and returns its index.
  • text.replace('hello', 'hi', 2): Replaces the first two occurrences of "hello" with "hi" in text.

The string methods discussed in this lesson are fundamental to effective text manipulation in Python, enabling you to format, search, and alter strings efficiently. These tools are indispensable for data processing, ensuring data integrity and simplifying interactions with text across various applications. By leveraging these methods, Python programmers can enhance the flexibility and robustness of their code, making it well-suited for a wide range of programming tasks involving textual data.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next