String Data and Methods

Introduction to Strings

  • Sequence of characters enclosed in single, double or triple quotes
  • Single quotes is used when string contains double quotes and vice versa
  • Triple quotes are used for multi-line strings
  • Strings are immutable. i.e. once created, they cannot be changed in-place.
  • Examples:
    1. str_1 = "Hello, I'm learning Python!"
    2. str_2 = 'Ram said, "I have a pen."'
    3. str_3 = """Hello, World!"""

Escaping Characters in Strings

  • Use backslash (\) to escape special characters in strings
  • Common escape sequences:
    1. \n - Newline \t - Tab \\ - Backslash \' - Single quote \" - Double quote
    Examples:
    1. str_1 = 'Hello, I\'m learning Python!'
    2. str_2 = 'I have a pen.\nIt is good'
    3. str_3 = 'I have a pen.\\nIt is good'

String Methods

  • Built-in functions that perform specific operations on strings and return a new string
  • String are immutable. i.e. cannot be changed in-place.
  • Examples of string methods:
    1. Position Related: Indexing, Slicing
    2. Generic: Concatenation, Repetition, Length
    3. Case Related: isupper(), islower(), istitle(), upper(), lower(), title(), swapcase()
    4. Data Check: isalpha(), isdigit(), isalnum(), isspace(), startswith(), endswith()
    5. Cleanup Related: strip(), split(), join(), find(), index(), replace(), count()

Indexing

  • Used to extract a single character from a specific position of string
  • Starts from 0, Negative indexing is also allowed
  • Examples:
    1. str_1 = "Python is fun" first_character= str_1[0] print(first_character) # P print(str_1[4]) # o print(str_1[-1]) # n print(str_1[7]) # i

Slicing

  • Used to extract a substring from a string based on position
  • Syntax: variable[start:stop:step]
  • Start is inclusive, stop is exclusive, step is optional
  • Examples:
    1. str_1 = "Python is fun" substring = str_1[0:6] print(substring) # Python print(str_1[0:6:2]) #Pto print(str_1[:3]) # Pyt print(str_1[10:]) # fun print(str_1[::-1]) # nuf si nohtyP

Concatenation

  • Used to combine two or more strings using + operator
  • Examples:
    1. str_1 = "Hello," str_2 = "World!" greeting = str_1 + " " + str_2 print(greeting) # Hello, World! print("Python " + "is " + "fun!") # Python is fun! print(str_1 + " Python") # Hello, Python

Repetition

  • Used to repeat a string multiple times using * operator
  • Examples:
    1. str_1 = "Hello " repeated_str = str_1 * 3 print(repeated_str) # Hello Hello Hello print("abc" * 5) # abcabcabcabcabc

Length

  • Used to get the number of characters in a string using len() function
  • Examples:
    1. str_1 = "Hello, World!" length = len(str_1) print(length) # 13 print(len("Python")) # 6 print(len("abc")) # 3

Checking Case of String

  • Used to check if characters in a string are uppercase, lowercase or title case
  • All characters must be of same case for these methods to return True
  • Examples:
    1. str_1 = "Hello, World!" print(str_1.isupper()) # False print(str_1.islower()) # False print("PYTHON".isupper()) # True print("python".islower()) # True print("Hello".istitle()) # True

Case Conversion

  • Used to change the case of characters in a string
  • Examples:
    1. str_1 = "Hello, World!" str_1_upper = str_1.upper() print(str_1_upper) # HELLO, WORLD! print(str_1.lower()) # hello, world! print(str_1.title()) # Hello, World! print(str_1.swapcase()) # hELLO, wORLD!

Checking value of String

  • Used to check if characters in a string are alphabetic, numeric, alphanumeric, whitespace
  • Examples:
    1. str_1 = "Hello" print(str_1.isalpha()) # True print(str_1.isdigit()) # False print("123".isdigit()) # True print("abc123".isalnum()) # True print(" ".isspace()) # True print("Hello123".isalpha()) # False

startswith and endswith

  • Used to check if a string starts or ends with a specific substring
  • Examples:
    1. str_1 = "2026-03-01.csv" print(str_1.startswith("2026")) # True print(str_1.endswith(".pdf")) # False print(str_1.startswith("03")) # False

strip

  • Used to remove leading and trailing whitespace (or other characters) from a string
  • lstrip and rstrip are used to remove leading and trailing characters respectively
  • Examples:
    1. str_1 = " Hello, World! " stripped_str = str_1.strip() print(stripped_str) # "Hello, World!" print("###Data # Fun###".strip("#")) # "Data # Fun" print("###Data###".lstrip("#")) # "Data###" print("###Data###".rstrip("#")) # "###Data"

split

  • Used to split a string into a list of substrings based on a specified delimiter (default is whitespace)
  • Examples:
    1. str_1 = "Hello, World!" split_str = str_1.split() print(split_str) # ["Hello,", "World!"] print("2026-03-01.csv".split("-")) # ["2026", "03", "01.csv"] print("apple,banana,orange".split(",")) # ["apple", "banana", "orange"]

join

  • Used to join a list of strings into a single string with a specified delimiter
  • Examples:
    1. str_list = ["Hello", "World"] joined_str = " ".join(str_list) print(joined_str) # "Hello World" print("-".join(["2026", "03", "01"])) # "2026-03-01" print(",".join(["apple", "banana", "orange"])) # "apple,banana,orange" print(".".join("apple")) # "a.p.p.l.e"

find and index

  • Used to find the index of the first occurrence of a specified substring in a string
  • .find() returns -1 but index() raises an error if substring is not found
  • Examples:
    1. str_1 = "Hello, World!" print(str_1.find("o")) # 4 print(str_1.find("o")) # 4 print(str_1.find("z")) # -1 print(str_1.index("z")) # Raises ValueError

replace

  • Used to replace occurrences of a specified substring with another substring
  • Examples:
    1. str_1 = "Hello, World!" replaced_str = str_1.replace("World", "Python") print(replaced_str) # "Hello, Python!" print("2026-03-01.csv".replace("-", "/")) # "2026/03/01.csv print("apple,banana,orange".replace(",", ";")) # "apple;banana;orange"

count

  • Used to count the number of occurrences of a specified substring in a string
  • Examples:
    1. str_1 = "Hello, World!" print(str_1.count("o")) # 2 print("banana,apple".count("banana")) # 1 print("2026-03-01.csv".count("-")) # 2 print("test_exercise.py".count(".pdf")) # 0