String Data and Methods
โ1. Strings
- 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" - Strings can be created using:
' ' โ Single quotes
" " โ Double quotes
""" """ โ Triple quotes for multi-line strings
Examples:
name = "Rabindra"course = 'Python'print(name)# โ Rabindraprint(course)# โ Python - 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 outsidestr_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! - 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
1.1 What is a String?
1.2 Creating Strings
1.3 When to use single and double quotes in Strings?
1.4 Multi-line Strings
2. Escape Character and Special Characters
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:\ncreates a new line.\tcreates a tab space.\\prints a backslash.str_1 = 'Hello, I\'m learning Python!'print(str_1)# โ Hello, I'm learning Python!str_2 = "Name:\tRabindra"print(str_2)# โ Name: Rabindrastr_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.- If we want to print
\n,\tas 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: \ntext = "\\n and \\t are escape sequences."print(text)# โ \n and \t are escape sequences.
2.1 Escape Character
2.2 Examples
2.3 Printing Literal Escape Sequences
3. Indexing and Slicing
- 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 -1print(text[0])# โ Pprint(text[-6])# โ Pprint(text[5])# โ nprint(text[-1])# โ n str_1 = "Python is fun"print(str_1[0])# โ Pprint(str_1[4])# โ oprint(str_1[-1])# โ nprint(str_1[7])# โ i- 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. str_1 = "Python is fun"print(str_1[0:6])# โ Pythonprint(str_1[0:6:2])# โ Ptoprint(str_1[:3])# โ Pytprint(str_1[10:])# โ funprint(str_1[::-1])# โ nuf si nohtyP- 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.
3.1 Indexing [ ]
3.2 Indexing Examples
3.3 Slicing [start:stop:step]
3.4 Slicing Examples
3.5 Strings are Immutable
4. Basic String Operations
- 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_2print(greeting)# โ Hello, World!print("Python " + "is " + "fun!")# โ Python is fun! - Repetition means repeating a string multiple times. The
*operator is used for string repetition. Example:str_1 = "Hello "repeated_str = str_1 * 3print(repeated_str)# โ Hello Hello Helloprint("abc" * 5)# โ abcabcabcabcabc len()is used to count the number of characters in a string. Example:str_1 = "Hello, World!"print(len(str_1))# โ 13print(len("Python"))# โ 6print(len("abc"))# โ 3 ๐ Spaces, commas, and symbols are also counted as characters.
4.1 Concatenation (+)
4.2 Repetition (*)
4.3 Length len()
5. String Methods
- 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.
- Case methods are used to check or change uppercase/lowercase letters.
Common Methods:
isupper()โ Checks if string is uppercaseislower()โ Checks if string is lowercaseistitle()โ Checks if each word starts with uppercase and remaining letters are lowercaseupper()โ Converts to uppercaselower()โ Converts to lowercasetitle()โ Converts to title caseswapcase()โ 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())# โ Trueprint("python".islower())# โ Trueprint("Hello".istitle())# โ Trueprint(str_1.upper())# โ HELLO, WORLD!print(str_1.lower())# โ hello, world!print(str_1.title())# โ Hello, World!print(str_1.swapcase())# โ hELLO, wORLD! - Data checking methods check what kind of characters a string contains.
Common Methods:
isalpha()โ Checks if all characters are alphabetsisdigit()โ Checks if all characters are digitsisalnum()โ Checks if all characters are alphabets or numbersisspace()โ Checks if all characters are whitespacestartswith()โ Checks if string starts with given textendswith()โ Checks if string ends with given text Examples:str_1 = "Hello"print(str_1.isalpha())# โ Trueprint(str_1.isdigit())# โ Falseprint("123".isdigit())# โ Trueprint("abc123".isalnum())# โ Trueprint(" ".isspace())# โ Trueprint("Hello123".isalpha())# โ Falsefile_name = "2026-03-01.csv"print(file_name.startswith("2026"))# โ Trueprint(file_name.endswith(".csv"))# โ Trueprint(file_name.endswith(".pdf"))# โ Falseprint(file_name.startswith("03"))# โ False - Cleanup methods remove unnecessary characters from a string.
Common Methods:
strip()โ Removes characters from both left and right sidelstrip()โ Removes characters from left side onlyrstrip()โ 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" 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"- These methods are used to find, replace, or count text inside a string.
Common Methods:
find()โ Finds index of text, returns -1 if not foundindex()โ Finds index of text, gives error if not foundreplace()โ Replaces textcount()โ 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"))# โ 4print(str_1.find("z"))# โ -1print(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)# โ 2print("banana,apple".count("banana"))# โ 1print("2026-03-01.csv".count("-"))# โ 2print("test_exercise.py".count(".pdf"))# โ 0
5.1 What are String Methods?
5.2 Case Methods ๐
5.3 Data Checking Methods โ
5.4 Cleanup Methods ๐งน
5.5 Split and Join Methods โ๏ธ ๐
5.6 Search, Replace, and Count Methods ๐ ๐ ๐ข
Practice QuestionsNot started
1. Storing Strings
Question 1 of 5
- Create a variable that stores your name and display it.
- Store the text
I'm learning Pythonin a variable and display it. - Store the text
Ram said, "I've a pen."in a variable and display it. - Store the text below in a variable as a multiline string and display it:
Dear Manager, I am on leave! Thanks - Store the following text in a variable and display it exactly as written:
\n and \t are escape sequences. We use \ to escape.
1.1 Practice storing and displaying strings:2. Indexing and Slicing
Question 2 of 5
- Find and display the first character.
- Find and display the character at index 8.
- Find and display the last character using negative indexing.
- Find the word
Pythonusing slicing and display it. - Find the word
funusing negative slicing and display it. - Find the text
lrnfrom the word learning and display it. - Reverse the string and display it.
- Find the substring from index 5 till the end and display it.
- Find the substring from the start till index 10 and display it.
2.1 Create a variablemy_strthat storesWe are learning Python and it's fun!3. Basic String Operations and Case Methods
Question 3 of 5
- Display
HelloWorldby concatenating both strings. - Create a variable
greetingsasHello Worldby concatenating both strings with a space and display it. - Create
my_strasHelloHelloHellousing string repetition. - Find and display the number of characters in
my_str. - Convert
greetingsto uppercase and display it. - Convert
greetingsto lowercase and display it. - Convert
greetingsto title case and display it. - Swap the case of characters in
greetingsand display it.
3.1 Create variablesstr_1 = "Hello"andstr_2 = "World"- Display
4. Data Checking and Cleanup Methods
Question 4 of 5
- Check and display if
str_1has alphabetic characters only. - Check and display if
str_1has numeric characters only. - Check and display if
str_2has alphanumeric characters only. - Check and display if
str_4contains only whitespace. - Check and observe whether
str_3starts withabc. - Check and observe whether
str_3ends with123. - Check and display if
str_1starts withHeand ends withlo. - Remove leading and trailing
#fromstr_3and display the result. - Remove leading
#fromstr_3and display the result. - Remove trailing
#fromstr_3and display the result.
4.1 Assignstr_1 = "Hello",str_2 = "134",str_3 = "##abc123##",str_4 = " "- Check and display if
5. String Data Manipulation
Question 5 of 5
- Assign
file_nameasreport_2026.pdf. Split and display the file name and extension. - Store
my_dateas2026-03-05. Split it into a list of year, month, and day. - Store
my_strasPYTHON. Usejoin()to displayP.Y.T.H.O.N. - Store
laptop_namesas["Dell", "HP", "Mac"]. Usejoin()to displayDell-HP-Mac. - Assign
str_1asHello, World!. ReplaceWorldwithPythonand display the result. - Assign
str_2as2026-03-01.csv. Replace-with/and display the result. - Assign
str_3asPineapple. Find at which indexapplestarts and display the result. - Assign
my_nameas your name. Count the number of vowels in it and display the result. Hint: Usecount()for a, e, i, o, u and add the results. - Assign
my_strasHello, World!. Count and display the occurrence of letterlin it.
5.1 Practice string data manipulation tasks:- Assign
