Fixed Top Ad (Local Preview)800x90 • Slot 6608427872

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!
Usage of Single and Double Quotes in Python
Usage of Single and Double Quotes in 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.
Python Special Character
Python Special Character
    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
Python String Indexing
Python String Indexing
    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.
Slicing in Python
Slicing in Python
    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!
String Concatenation and Repetition in Python
String Concatenation and Repetition in Python
    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.
Methods available for Python String with description
Methods available for Python 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
Ad PlaceholderSlot: 7421026683

Practice QuestionsNot started

  1. 1. Storing Strings

    Question 1 of 5

      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

      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 indexing 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

      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

      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

      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.
Ad PlaceholderSlot: 5413242224