String manipulation in Python

working with strings in python

String manipulation in Python is essential for working with and processing textual data. Python provides a variety of built-in methods and operators to handle strings effectively.

Here’s a breakdown of common string manipulation techniques:

Basic String Operations

  • String Concatenation You can join multiple strings using the + operator or join() method.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2  # Concatenation using '+'
print(result)  # Output: "Hello World"
  • String Repetition You can repeat a string multiple times using the * operator.
result = "Hello" * 3
print(result)  # Output: "HelloHelloHello"
  • String Length You can find the length of a string using len().
text = "Python"
print(len(text))  # Output: 6

String Slicing

You can extract parts of a string using slicing.

text = "Hello, Python!"
# Slicing the string from index 7 to the end
sliced = text[7:]
print(sliced)  # Output: "Python!"
  • Basic syntax: string[start:end:step]
    • start: Index where the slice starts (inclusive).
    • end: Index where the slice ends (exclusive).
    • step: Steps for slicing (default is 1).
text = "Hello, Python!"
# Slicing with step
sliced = text[::2]  # Every 2nd character
print(sliced)  # Output: "Hoo yhn"

String Methods

  • Changing Case You can change the case of a string using the following methods:
    • .lower(): Converts all characters to lowercase.
    • .upper(): Converts all characters to uppercase.
    • .capitalize(): Capitalizes the first letter.
text = "hello"
print(text.upper())      # Output: "HELLO"
print(text.lower())      # Output: "hello"
print(text.capitalize()) # Output: "Hello"
  • Stripping Whitespace To remove leading and trailing whitespaces:
    • .strip() – Removes both leading and trailing spaces.
    • .lstrip() – Removes leading spaces.
    • .rstrip() – Removes trailing spaces.
text = "   Hello, Python!   "
print(text.strip())  # Output: "Hello, Python!"
  • Replacing Substrings You can replace parts of a string using .replace().
text = "Hello, world!"
result = text.replace("world", "Python")
print(result)  # Output: "Hello, Python!"
  • Splitting Strings The .split() method splits a string into a list of substrings based on a delimiter (space by default).
text = "apple, banana, cherry"
result = text.split(", ")
print(result)  # Output: ['apple', 'banana', 'cherry']
  • Joining Strings To join a list of strings into one string, use .join().
words = ['apple', 'banana', 'cherry']
result = ", ".join(words)
print(result)  # Output: "apple, banana, cherry"

String Searching

  • Find and Index
    • .find(substring): Returns the index of the first occurrence of the substring or -1 if not found.
    • .index(substring): Similar to find(), but raises an error if the substring is not found.
text = "Hello, Python!"
print(text.find("Python"))  # Output: 7
print(text.index("Python"))  # Output: 7
  • Checking for Substring .in operator: Checks if a substring exists within the string.
text = "Hello, Python!"
print("Python" in text)  # Output: True
print("Java" in text)    # Output: False

String Formatting

Python provides several ways to format strings.

  • f-Strings (Python 3.6+) Using f-strings to embed expressions inside string literals.
name = "Jasmeet"
age = 30
result = f"Hello, my name is {name} and I am {age} years old."
print(result)  # Output: "Hello, my name is Jasmeet and I am 30 years old."
  • format() Method This method allows more flexibility in formatting.
name = "Bob"
age = 25
result = "Hello, my name is {} and I am {} years old.".format(name, age)
print(result)  # Output: "Hello, my name is Bob and I am 25 years old."
  • Old-style Formatting (%) This is the old way of formatting strings.
name = "Charlie"
age = 40
result = "Hello, my name is %s and I am %d years old." % (name, age)
print(result)  # Output: "Hello, my name is Charlie and I am 40 years old."

String Testing Methods

  • Checking if a String is Alphanumeric .isalnum(): Returns True if all characters are alphanumeric (letters and numbers).
text = "Hello123"
print(text.isalnum())  # Output: True
  • Checking if a String is Numeric .isnumeric(): Returns True if all characters are digits.
text = "12345"
print(text.isnumeric())  # Output: True
  • Checking if a String is Alphabetic .isalpha(): Returns True if all characters are alphabetic.
text = "Hello"
print(text.isalpha())  # Output: True

Escape Characters

Sometimes, you may want to use special characters in your strings (like quotes, newlines, etc.). You can use escape characters for that.

  • \n: Newline
  • \t: Tab
  • \': Single quote
  • \": Double quote
  • \\: Backslash
text = "Hello\nWorld!"
print(text)
# Output:
# Hello
# World!

Multiline Strings

You can use triple quotes (''' or """) for multi-line strings.

text = """This is a
multi-line string."""
print(text)

Output

This is a
multi-line string.

Common String Operations:

  • Concatenation: +
  • Repetition: *
  • Length: len()
  • Slicing: string[start:end:step]
  • Case Conversion: .lower(), .upper(), .capitalize()
  • Whitespace: .strip(), .lstrip(), .rstrip()
  • Replace: .replace()
  • Split: .split()
  • Join: .join()
  • Find: .find(), .index()
  • Substring Check: 'substring' in string
  • String Formatting: f-strings, .format(), % formatting
  • Testing: .isalnum(), .isnumeric(), .isalpha()
No questions available.