String Methods

  • String methods in Python are built-in functions that allow you to manipulate and work with text data easily. Since strings are one of the most commonly used data types, understanding string methods is essential for every Python programmer.
  • String Methods in Python


    upper() and lower()

    • upper() converts all characters in a string to uppercase.

    • lower() converts all characters in a string to lowercase.

Converting String Case

This example converts a string into uppercase and lowercase.

text = "Python Programming"
print(text.upper())
print(text.lower())
  • strip()

    The strip() method removes extra spaces from the beginning and end of a string.

Removing Extra Spaces

This example removes leading and trailing spaces from a string.

text = "  Python  "
print(text.strip())
  • replace()

    The replace() method replaces a word or character with another value.

Replacing Text in a String

This example replaces a word in the string.

text = "I like Java"
print(text.replace("Java", "Python"))
  • split()

    The split() method splits a string into a list based on a separator.

Splitting a String

This example splits a sentence into words.

text = "Python is easy"
print(text.split())
  • join()

    The join() method joins elements of a list into a single string.

Joining List into String

This example joins list items using a space.

words = ["Python", "is", "fun"]
print(" ".join(words))
  • find()

    The find() method returns the index of the first occurrence of a value.
    Returns -1 if the value is not found.

Finding Text Position

This example finds the position of a word in a string.

text = "Learn Python"
print(text.find("Python"))
  • count()

    The count() method counts how many times a value appears in a string.

Counting Occurrences

This example counts how many times a character appears.

text = "banana"
print(text.count("a"))
  • Escape Characters (\n, \t, etc.)

    Escape characters are used to format text inside strings.

    Escape

    Meaning

    \n

    New line

    \t

    Tab space

    \\

    Backslash

    \'

    Single quote

    \"

    Double quote

print("Python\nProgramming")
print("Python\tProgramming")