replace(), join(), split(), rsplit(), and splitlines() methods in Python

1. replace() Method

Purpose: Replaces occurrences of a substring with another substring.
Syntax:

python

string.replace(old, new[, count])
  • old: Substring to replace.
  • new: Substring to replace with.
  • count (optional): Maximum number of replacements (default: all).

Examples:

Example 1: Basic Replacement

python

text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text)  # Output: "Hello Python"

Example 2: Limiting Replacements (count)

python

text = "apple apple apple"
new_text = text.replace("apple", "orange", 2)
print(new_text)  # Output: "orange orange apple"

2. join() Method

Purpose: Joins an iterable (list, tuple, etc.) of strings into a single string using a separator.
Syntax:

python

separator.join(iterable)
  • iterable: Must contain strings (e.g., listtuple).

Examples:

Example 1: Joining a List with a Space

python

words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)  # Output: "Python is awesome"

Example 2: Joining with a Comma

python

fruits = ["apple", "banana", "cherry"]
csv = ",".join(fruits)
print(csv)  # Output: "apple,banana,cherry"

3. split() Method

Purpose: Splits a string into a list based on a delimiter.
Syntax:

python

string.split(sep=None, maxsplit=-1)
  • sep: Delimiter (default: whitespace).
  • maxsplit: Maximum splits (default: all).

Examples:

Example 1: Splitting by Comma

python

text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits)  # Output: ['apple', 'banana', 'cherry']

Example 2: Limiting Splits (maxsplit)

python

text = "one two three four"
parts = text.split(" ", 2)
print(parts)  # Output: ['one', 'two', 'three four']

4. rsplit() Method

Purpose: Similar to split(), but splits from the right (end of string).
Syntax:

python

string.rsplit(sep=None, maxsplit=-1)
  • sep: Delimiter (default: whitespace).
  • maxsplit: Maximum splits (default: all).

Examples:

Example 1: Basic rsplit()

python

text = "apple,banana,cherry"
fruits = text.rsplit(",")
print(fruits)  # Output: ['apple', 'banana', 'cherry'] (same as split)

Example 2: Limiting Splits from the Right

python

text = "one two three four"
parts = text.rsplit(" ", 2)
print(parts)  # Output: ['one two', 'three', 'four']

5. splitlines() Method

Purpose: Splits a string at line breaks (\n\r\n, etc.).
Syntax:

python

string.splitlines([keepends=False])
  • keepends: If True, keeps line breaks (default: False).

Examples:

Example 1: Basic splitlines()

python

text = "Line 1\nLine 2\r\nLine 3"
lines = text.splitlines()
print(lines)  # Output: ['Line 1', 'Line 2', 'Line 3']

Example 2: Keeping Line Breaks (keepends=True)

python

text = "Hello\nWorld"
lines = text.splitlines(keepends=True)
print(lines)  # Output: ['Hello\n', 'World']

Summary Table

MethodPurposeExample
replace()Replace substrings"abc".replace("a", "x") → "xbc"
join()Combine strings with a separator",".join(["a", "b"]) → "a,b"
split()Split string by delimiter (left-to-right)"a,b,c".split(",") → ["a", "b", "c"]
rsplit()Split string by delimiter (right-to-left)"a b c".rsplit(" ", 1) → ["a b", "c"]
splitlines()Split by line breaks"a\nb".splitlines() → ["a", "b"]

These methods are essential for string manipulation in Python. Let me know if you need further clarification! 🚀

Similar Posts

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • What is Python library Complete List of Python Libraries

    In Python, a library is a collection of pre-written code that you can use in your programs. Think of it like a toolbox full of specialized tools. Instead of building every tool from scratch, you can use the tools (functions, classes, modules) provided by a library to accomplish tasks more efficiently.   Here’s a breakdown…

  • Type Conversion Functions

    Type Conversion Functions in Python 🔄 Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples: 1. int(x) 🔢 Converts x to an integer. Python 2. float(x) afloat Converts x to a floating-point number. Python 3. str(x) 💬 Converts x…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

Leave a Reply

Your email address will not be published. Required fields are marked *