String Data and Methods

โœ•

1. Strings

    1.1 What is a String?
    1. A string is a data type in Python used to store text data such as words, sentences, numbers written as text, symbols, and spaces. A string is written as a sequence of characters enclosed inside quotes. Examples of Text Data: "Python", 'Hello, World!', '12345', "๐Ÿ˜Š", "report_2026.pdf"
    1.2 Creating Strings
    1. Strings can be created using: ' ' โžœ Single quotes " " โžœ Double quotes """ """ โžœ Triple quotes for multi-line strings Examples: name = "Rabindra" course = 'Python'print(name) # โžœ Rabindra print(course) # โžœ Python
    1.3 When to use single and double quotes in Strings?
    1. Sometimes, the text we want to store already contains quotes. In such cases, choosing the correct quote type helps us avoid errors. str_1 = 'Hello, I'm learning Python!' โŒ Problem: Single quote inside single-quoted string. Python sees the quote in I'm and thinks the string has ended. So it gives an error. โœ… Solution: Use double quotes outside str_1 = "Hello, I'm learning Python!" print(str_1) # โžœ Hello, I'm learning Python! Tip: ๐Ÿ’ฌ Single quotes (' ') are useful when the string contains double quotes. str_1 = 'Ram said, "I have a pen."' print(str_1) # โžœ Ram said, "I have a pen." ๐Ÿ’ฌ Double quotes (" ") are useful when the string contains single quotes. str_2 = "Hello, I'm learning Python!" print(str_2) # โžœ Hello, I'm learning Python!
    1.4 Multi-line Strings
    1. Triple quotes are used to create multi-line strings. Example: message = """Dear Manager, I am on leave! Thanks""" print(message)Output: Dear Manager, I am on leave! Thanks

2. Escape Character and Special Characters

    2.1 Escape Character
    1. text = "Name:\tRabindra" print(text)Output: Name: Rabindra ๐Ÿ˜• Why did Python show extra space instead of printing \t? This happened because \t has a special meaning in Python strings. \t is an escape sequence that creates a tab space. The backslash \ is called an escape character. It is used to give special meaning to the character that comes after it. Few Special Characters:\n creates a new line. \t creates a tab space. \\ prints a backslash.
    2.2 Examples
    1. str_1 = 'Hello, I\'m learning Python!' print(str_1) # โžœ Hello, I'm learning Python! str_2 = "Name:\tRabindra" print(str_2) # โžœ Name: Rabindra str_3 = "This is a backslash: \\" print(str_3) # โžœ This is a backslash: \ str_4 = "I have a pen.\nIt is good." print(str_4)Output: I have a pen. It is good.
    2.3 Printing Literal Escape Sequences
    1. If we want to print \n, \t as normal text instead of creating a new line, we need to escape the backslash. Example: text = "This is newline symbol: \\n" print(text) # โžœ This is newline symbol: \n text = "\\n and \\t are escape sequences." print(text) # โžœ \n and \t are escape sequences.

3. Indexing and Slicing

    3.1 Indexing [ ]
    1. Indexing is used to access a single character from a string. Each character in a string can be accessed using positive or negative index. Example: text = "Python" Index positions: P y t h o n 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 print(text[0]) # โžœ P print(text[-6]) # โžœ P print(text[5]) # โžœ n print(text[-1]) # โžœ n
    3.2 Indexing Examples
    1. str_1 = "Python is fun"print(str_1[0]) # โžœ P print(str_1[4]) # โžœ o print(str_1[-1]) # โžœ n print(str_1[7]) # โžœ i
    3.3 Slicing [start:stop:step]
    1. Slicing is used to extract a part of a string. Syntax: variable[start:stop:step] start โžœ Starting index stop โžœ Stopping index, but not included step โžœ Number of characters to skip ๐Ÿ“Œ Start is included. ๐Ÿ“Œ Stop is not included. ๐Ÿ“Œ Step is optional. ๐Ÿ“Œ If start is not given, slicing begins from the start. ๐Ÿ“Œ If stop is not given, slicing continues till the end.
    3.4 Slicing Examples
    1. str_1 = "Python is fun"print(str_1[0:6]) # โžœ 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
    3.5 Strings are Immutable
    1. Strings are immutable. This means once a string is created, it cannot be changed directly in-place. If we apply a string method, Python creates a new string instead of changing the original string. Example: text = "hello" text[2] = "P" โš ๏ธ This line gives an error because individual characters in a string cannot be changed directly.

4. Basic String Operations

    4.1 Concatenation (+)
    1. Concatenation means combining two or more strings. The + operator is used for string concatenation. Example: str_1 = "Hello," str_2 = "World!"greeting = str_1 + " " + str_2 print(greeting) # โžœ Hello, World! print("Python " + "is " + "fun!") # โžœ Python is fun!
    4.2 Repetition (*)
    1. Repetition means repeating a string multiple times. The * operator is used for string repetition. Example: str_1 = "Hello "repeated_str = str_1 * 3 print(repeated_str) # โžœ Hello Hello Hello print("abc" * 5) # โžœ abcabcabcabcabc
    4.3 Length len()
    1. len() is used to count the number of characters in a string. Example: str_1 = "Hello, World!"print(len(str_1)) # โžœ 13 print(len("Python")) # โžœ 6 print(len("abc")) # โžœ 3 ๐Ÿ“Œ Spaces, commas, and symbols are also counted as characters.

5. String Methods

    5.1 What are String Methods?
    1. String methods are built-in operations used to work with text. They help us: ๐Ÿ”  Change case โœ… Check text ๐Ÿงน Clean text โœ‚๏ธ Split text ๐Ÿ”— Join text ๐Ÿ” Search text ๐Ÿ” Replace text ๐Ÿ”ข Count text ๐Ÿ“Œ Since strings are immutable, string methods usually return a new string instead of changing the original string.
    5.2 Case Methods ๐Ÿ” 
    1. Case methods are used to check or change uppercase/lowercase letters. Common Methods: isupper() โžœ Checks if string is uppercase islower() โžœ Checks if string is lowercase istitle() โžœ Checks if each word starts with uppercase and remaining letters are lowercase upper() โžœ Converts to uppercase lower() โžœ Converts to lowercase title() โžœ Converts to title case swapcase() โžœ Swaps uppercase and lowercase Examples: str_1 = "Hello, World!"print(str_1.isupper()) # โžœ False (returns True only when all characters are in uppercase) print(str_1.islower()) # โžœ False (returns True only when all characters are in lowercase) print("PYTHON".isupper()) # โžœ True print("python".islower()) # โžœ True print("Hello".istitle()) # โžœ True print(str_1.upper()) # โžœ HELLO, WORLD! print(str_1.lower()) # โžœ hello, world! print(str_1.title()) # โžœ Hello, World! print(str_1.swapcase()) # โžœ hELLO, wORLD!
    5.3 Data Checking Methods โœ…
    1. Data checking methods check what kind of characters a string contains. Common Methods: isalpha() โžœ Checks if all characters are alphabets isdigit() โžœ Checks if all characters are digits isalnum() โžœ Checks if all characters are alphabets or numbers isspace() โžœ Checks if all characters are whitespace startswith() โžœ Checks if string starts with given text endswith() โžœ Checks if string ends with given text Examples: 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 file_name = "2026-03-01.csv"print(file_name.startswith("2026")) # โžœ True print(file_name.endswith(".csv")) # โžœ True print(file_name.endswith(".pdf")) # โžœ False print(file_name.startswith("03")) # โžœ False
    5.4 Cleanup Methods ๐Ÿงน
    1. Cleanup methods remove unnecessary characters from a string. Common Methods: strip() โžœ Removes characters from both left and right side lstrip() โžœ Removes characters from left side only rstrip() โžœ Removes characters from right side only Examples: str_1 = " Hello, World! "clean_str = str_1.strip() print(clean_str) # โžœ "Hello, World!" print("###Data # Fun###".strip("#")) # โžœ "Data # Fun" print("###Data###".lstrip("#")) # โžœ "Data###" print("###Data###".rstrip("#")) # โžœ "###Data"
    5.5 Split and Join Methods โœ‚๏ธ ๐Ÿ”—
    1. split() โžœ Breaks a string into a list based on split character provided. join() โžœ Joins a list of strings into one string. split() Examples: str_1 = "Hello, World!" print(str_1.split()) # โžœ ["Hello,", "World!"] date_separated = "2026-03-01.csv".split("-") print(date_separated) # โžœ ["2026", "03", "01.csv"] print("apple,banana,orange".split(",")) # โžœ ["apple", "banana", "orange"] join() Examples: str_list = ["Hello", "World"] print(" ".join(str_list)) # โžœ "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"
    5.6 Search, Replace, and Count Methods ๐Ÿ” ๐Ÿ” ๐Ÿ”ข
    1. These methods are used to find, replace, or count text inside a string. Common Methods: find() โžœ Finds index of text, returns -1 if not found index() โžœ Finds index of text, gives error if not found replace() โžœ Replaces text count() โžœ Counts text occurrence find() and index() Examples: str_1 = "Hello, World!"print(str_1.find("o")) # โžœ 4 (As o occurs first at index 4) print(str_1.index("o")) # โžœ 4 print(str_1.find("z")) # โžœ -1 print(str_1.index("z")) # โžœ ValueError โš ๏ธ This line gives an error because "z" is not found. ๐Ÿ“Œ find() returns -1 if text is not found. ๐Ÿ“Œ index() raises ValueError if text is not found. replace() Examples: str_1 = "Hello, World!" new_str = str_1.replace("World", "Python") print(new_str) # โžœ "Hello, Python!" print("2026-03-01.csv".replace("-", "/")) # โžœ "2026/03/01.csv" print("apple,banana,orange".replace(",", ";")) # โžœ "apple;banana;orange" count() Examples: str_1 = "Hello, World!" count_of_o = str_1.count("o") print(count_of_o) # โžœ 2 print("banana,apple".count("banana")) # โžœ 1 print("2026-03-01.csv".count("-")) # โžœ 2 print("test_exercise.py".count(".pdf")) # โžœ 0

Practice QuestionsNot started

  1. 1. Storing Strings

    Question 1 of 5

      1.1 Practice storing and displaying strings:
      1. Create a variable that stores your name and display it.
      2. Store the text I'm learning Python in a variable and display it.
      3. Store the text Ram said, "I've a pen." in a variable and display it.
      4. Store the text below in a variable as a multiline string and display it: Dear Manager, I am on leave! Thanks
      5. Store the following text in a variable and display it exactly as written: \n and \t are escape sequences. We use \ to escape.
  2. 2. Indexing and Slicing

    Question 2 of 5

      2.1 Create a variable my_str that stores We are learning Python and it's fun!
      1. Find and display the first character.
      2. Find and display the character at index 8.
      3. Find and display the last character using negative indexing.
      4. Find the word Python using slicing and display it.
      5. Find the word fun using negative slicing and display it.
      6. Find the text lrn from the word learning and display it.
      7. Reverse the string and display it.
      8. Find the substring from index 5 till the end and display it.
      9. Find the substring from the start till index 10 and display it.
  3. 3. Basic String Operations and Case Methods

    Question 3 of 5

      3.1 Create variables str_1 = "Hello" and str_2 = "World"
      1. Display HelloWorld by concatenating both strings.
      2. Create a variable greetings as Hello World by concatenating both strings with a space and display it.
      3. Create my_str as HelloHelloHello using string repetition.
      4. Find and display the number of characters in my_str.
      5. Convert greetings to uppercase and display it.
      6. Convert greetings to lowercase and display it.
      7. Convert greetings to title case and display it.
      8. Swap the case of characters in greetings and display it.
  4. 4. Data Checking and Cleanup Methods

    Question 4 of 5

      4.1 Assign str_1 = "Hello", str_2 = "134", str_3 = "##abc123##", str_4 = " "
      1. Check and display if str_1 has alphabetic characters only.
      2. Check and display if str_1 has numeric characters only.
      3. Check and display if str_2 has alphanumeric characters only.
      4. Check and display if str_4 contains only whitespace.
      5. Check and observe whether str_3 starts with abc.
      6. Check and observe whether str_3 ends with 123.
      7. Check and display if str_1 starts with He and ends with lo.
      8. Remove leading and trailing # from str_3 and display the result.
      9. Remove leading # from str_3 and display the result.
      10. Remove trailing # from str_3 and display the result.
  5. 5. String Data Manipulation

    Question 5 of 5

      5.1 Practice string data manipulation tasks:
      1. Assign file_name as report_2026.pdf. Split and display the file name and extension.
      2. Store my_date as 2026-03-05. Split it into a list of year, month, and day.
      3. Store my_str as PYTHON. Use join() to display P.Y.T.H.O.N.
      4. Store laptop_names as ["Dell", "HP", "Mac"]. Use join() to display Dell-HP-Mac.
      5. Assign str_1 as Hello, World!. Replace World with Python and display the result.
      6. Assign str_2 as 2026-03-01.csv. Replace - with / and display the result.
      7. Assign str_3 as Pineapple. Find at which index apple starts and display the result.
      8. Assign my_name as your name. Count the number of vowels in it and display the result. Hint: Use count() for a, e, i, o, u and add the results.
      9. Assign my_str as Hello, World!. Count and display the occurrence of letter l in it.