Data Type: Strings
In Python, data types define the type of data a variable can hold. Two fundamental data types are Strings and Numbers. Understanding these is essential for building any Python program.
Strings
A string is a sequence of characters enclosed in single ('), double ("), or triple quotes (''' or """`).
Think of a string as a necklace made of beads, where:
- Each bead is a character (a letter, number, or symbol).
- The entire necklace is the string.
Creating Strings
Strings can be written in:
- Single quotes: 'Hello'
- Double quotes: "Hello"
- Triple quotes: '''Hello''' or """Hello""" (used for multi-line text).
Examples:
# Examples of strings
name = "John Doe" # Double quotes
greeting = 'Hello, World!' # Single quotes
multiline = """This is a
multi-line string.""" # Triple quotes
String Analogy: A Name Tag
Imagine a name tag with your name on it:
The name itself is the string: "John Doe".
- The quotes are the edges of the name tag that keep the text together.
- Without the edges (quotes), Python wouldn't know where your string starts and ends.
#Which of these are valid strings. Fix the ones that are not valid.
first_name = "Kevin'
middle_name = 'John"
last_name = "Smith"
lucky_number = 1234
apartment_number = "A123"
street_name = """Elandale
Lane"""
state_county = '''California
Alameda County'''
country = '''United
States"""
Accessing Parts of a String (Indexing)
A string is like a necklace made of beads, where each bead represents a character (a letter, number, or symbol). The position of each bead on the necklace is called its index, and the first bead starts at index 0. You can think of the string as a necklace with numbered beads, where you can refer to each bead (character) by its position.
name = "Alice"
print(name[0]) # Access the bead at index 0 (Output: A)
print(name[4]) # Access the bead at index 4 (Output: e)
This means:
- Bead 0: A
- Bead 1: l
- Bead 2: i
- Bead 3: c
- Bead 4: e
By knowing the position (index), you can "pick out" any bead from the necklace!
What is Negative Indexing?
In Python, negative indexing allows you to count characters from the end of the string, rather than the beginning.
Imagine a necklace of beads again, where:
- Positive indexes count from the first bead (left to right), starting at 0.
- Negative indexes count from the last bead (right to left), starting at -1.
###How Negative Indexing Works
Positive Indexing:
Necklace: P y t h o n
Indexes: 0 1 2 3 4 5
Negative Indexing:
Necklace: P y t h o n
Indexes: -6 -5 -4 -3 -2 -1
###Why Use Negative Indexing?
Negative indexing is useful when:
-
You want to work from the end of the string: For example, you might want the last character of a string without calculating its length.
-
Shortcuts for slicing: You can use negative indexes to easily slice parts of a string.
String Exercises
Now that we have learnt how to create a string and how to access individual characters of a string, its time to practice.
#Objective 1: Create two string variables, first_name that stores your first name and last_name that stores your last name.
#Print the inititials of your name using these variables.
#Example. My first name is Pawan and last name is Mittal, and the program shall print PM
#Objective 2: Print first and last character of the word using positive indexing.
word = "Python"
#Objective 3: Print first and last character of the word using negative indexing.
word = "Python"
word = "Python"
print(word[2]) #What is the output of this print statement
#Objective 4: Print the same character using negative index
Common String Operations
Concatenation: Combine strings using the + operator. Concatenation is the process of joining two or more strings together using the + operator. It’s like gluing two pieces of paper together to make one.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # Adding a space between names
print(full_name) # Output: John Doe
Key Notes: Only strings can be concatenated. If you try to concatenate a string with a number, you must first convert the number to a string using str().
age = 25
message = "I am " + str(age) + " years old."
print(message) # Output: I am 25 years old.
Repetition: Repeat strings using the * operator. Repetition involves duplicating a string a specified number of times using the * operator. Think of it as stacking identical Lego blocks.
Example:
word = "Hi"
print(word * 3) # Output: HiHiHi
Key Notes:
- The number (n) after the * operator specifies how many times the string will be repeated.
- If n is 0 or negative, the result is an empty string.
print("Python" * 0) # Output: (empty string)
Accessing Characters: Indexing & Slicing
Indexing: Accessing a Single Element
Indexing refers to retrieving a single item (like a character in a string) based on its position (index) in the sequence.
Purpose: To extract one specific item.
- Input: A single position (index).
- Output: A single element (e.g., one character from a string).
Example in Strings:
word = "Python"
print(word[0]) # Output: 'P' (first character)
print(word[-1]) # Output: 'n' (last character)
Slicing: Extracting a Subset
Slicing refers to retrieving a subset of items (a range) from the sequence by specifying a start and end index. It returns a new sequence containing multiple items from the original.
- Purpose: To extract a range or subset of items.
- Input: Start index, end index, and optionally a step.
- Output: A new sequence (e.g., substring in a string).
Example in Strings:
word = "Python"
print(word[0:3]) # Output: 'Pyt' (characters from index 0 to 2)
print(word[2:]) # Output: 'thon' (from index 2 to the end)
Slicing Without Start or End Index
When slicing a string (or any sequence) in Python, the start and end indexes are optional. Leaving them out has specific meanings:
1. No Start Index ([:end])
- If the start index is omitted, slicing starts from the beginning of the string.
- This is equivalent to setting start = 0.
Example:
word = "Python"
print(word[:3]) # Output: 'Pyt' (characters from the beginning to index 2)
2. No End Index ([start:])
- If the end index is omitted, slicing continues to the end of the string.
- This is equivalent to setting end = len(string).
Example:
word = "Python"
print(word[3:]) # Output: 'hon' (characters from index 3 to the end)
3. No Start and End Index ([:])
- If both the start and end indexes are omitted, the slice includes the entire string.
- This is equivalent to copying the whole string.
Example:
word = "Python"
print(word[:]) # Output: 'Python' (the entire string)
Practice Slicing Now that we have learnt about slicing, lets practice it.
#Objecive 1: create a variable with your full name, i,e name = "Pawan Mittal".
#Slice this variable into as many variables as there are part in your name and print them.
#For example, if you have only a first and last name slicing your name will generate 2 new variables
#If you have a first name, middle name and a last name , slicing will lead to 3 variables
Common String Methods
- The len() function returns the number of characters in a string, including spaces, punctuation, and special characters.
It’s useful for checking the size of strings before performing operations like slicing or validation.
text = "Hello, world!"
print(len(text)) # Output: 13
- find(): Finds the index of the first occurrence of a substring. Returns -1 if not found.
text = "Python is fun"
print(text.find("is")) # Output: 7
print(text.find("Java")) # Output: -1
- lower() and upper(): Change case.
name = "Alice"
print(name.upper()) # Output: ALICE
print(name.lower()) # Output: alice
- replace(): Replace parts of a string (like editing text on a signboard).
text = "I like Java"
print(text.replace("Java", "Python")) # Output: I like Python
- strip(): Remove extra spaces (like trimming paper edges).
messy = " Hello "
print(messy.strip()) # Output: Hello
- split() and join(): Break a string into pieces or combine pieces into a string.
sentence = "Python is fun"
words = sentence.split() # Splits into ['Python', 'is', 'fun']
print(" ".join(words)) # Joins back into "Python is fun"
Lets practice common string methods.
# 1. Convert to Uppercase
# Problem Statement:
# Write a program that converts the string "hello world" to uppercase using the .upper() method.
# Example Output:
# "HELLO WORLD"
# 2. Convert to Lowercase
# Problem Statement:
# Write a program that converts the string "HELLO WORLD" to lowercase using the .lower() method.
# Example Output:
# "hello world"
# 3. Remove Extra Spaces
# Problem Statement:
# Write a program to remove extra spaces from the string " Python Programming " using the .strip() method.
# Example Output:
# "Python Programming"
#4: In exercise 3 how can we validate that the extra characters have been removed?
# 5. Find the Position of a Substring
# Problem Statement:
# Write a program that finds the position of the word "Python" in the string "I am learning Python programming." using the .find() method.
# Example Output:
# 15 (the starting index of "Python")
# 6. Replace a Word
# Problem Statement:
# Write a program that replaces the word "bad" with "good" in the string "This is a bad example." using the .replace() method.
# Example Output:
# "This is a good example."
# 7. Split a Sentence into Words
# Problem Statement:
# Write a program that splits the string "Python is fun to learn" into individual words using the .split() method.
# Example Output:
# ["Python", "is", "fun", "to", "learn"]