Strings in Python
In the previous lesson, we learned about Tuples, Sets, and Dictionaries in Python. Today, we will learn about Strings, one of the most important and commonly used data types in Python programming.
Strings are used to store and manipulate text data such as names, messages, passwords, and sentences.
What is a String?
A String is a sequence of characters enclosed inside:
- Single quotes "' '"
- Double quotes "" ""
- Triple quotes "''' '''" or """" """"
Example
name = "Python Programming"
print(name)
Output
Python Programming
Creating Strings
Single Quotes
language = 'Python'
Double Quotes
course = "Programming"
Triple Quotes
Triple quotes are used for multi-line strings.
message = """
Welcome to Python Programming
"""
Accessing Characters in a String
Each character in a string has an index number.
Python indexing starts from "0".
Example
text = "Python"
print(text[0])
print(text[1])
Output
P
y
Negative Indexing
Negative indexing accesses characters from the end.
Example
text = "Python"
print(text[-1])
Output
n
String Length
The "len()" function returns the number of characters in a string.
Example
text = "Python"
print(len(text))
Output
6
String Slicing
String slicing extracts part of a string.
Example
text = "Python Programming"
print(text[0:6])
Output
Python
String Concatenation
Concatenation means joining strings together.
Example
first_name = "Augustine"
last_name = "Owino"
full_name = first_name + " " + last_name
print(full_name)
Output
Augustine Owino
String Repetition
The "*" operator repeats strings.
Example
text = "Python "
print(text * 3)
Output
Python Python Python
Common String Methods
Python provides many built-in methods for working with strings.
upper()
Converts text to uppercase.
Example
text = "python"
print(text.upper())
Output
PYTHON
lower()
Converts text to lowercase.
Example
text = "PYTHON"
print(text.lower())
Output
python
strip()
Removes spaces from the beginning and end.
Example
text = " Python "
print(text.strip())
Output
Python
replace()
Replaces part of a string.
Example
text = "Python Programming"
print(text.replace("Python", "Java"))
Output
Java Programming
split()
Splits a string into a list.
Example
text = "Python Java C++"
print(text.split())
Output
['Python', 'Java', 'C++']
Checking Strings
Python provides methods to check string contents.
Method| Meaning
"isdigit()"| Checks if all characters are numbers
"isalpha()"| Checks if all characters are letters
"isalnum()"| Checks if string contains letters and numbers
Example
text = "Python123"
print(text.isalnum())
Output
True
Escape Characters in Strings
Escape characters are special characters used inside strings.
Escape Character| Meaning
"\n"| New Line
"\t"| Tab Space
"\""| Double Quotes
"\"| Backslash
Example
text = "Python\nProgramming"
print(text)
text = "Python\tProgramming"
print(text)
text = "He said, \"Python is easy\""
print(text)
text = "C:\Users\Augustine"
print(text)
Output
Python
Programming
Python Programming
He said, "Python is easy"
C:\Users\Augustine
String Membership Operators
Membership operators are used to check whether a substring exists inside a string.
Example
text = "Python Programming"
print("Python" in text)
print("Java" in text)
Output
True
False
Looping Through a String
You can use a "for" loop to access each character in a string.
Example
text = "Python"
for letter in text:
print(letter)
Output
P
y
t
h
o
n
String Formatting
String formatting allows us to insert variables into strings.
Example
name = "Augustine"
age = 22
print(f"My name is {name} and I am {age} years old.")
Output
My name is Augustine and I am 22 years old.
Immutability of Strings
Strings are immutable, meaning they cannot be changed after they are created.
Example
text = "Python"
This will cause an error
text[0] = "J"
text = "Jython"
print(text)
Output
Jython
Practical Example
name = input("Enter your name: ")
print("Welcome", name)
print("Your name has", len(name), "characters")
print("Uppercase:", name.upper())
print("Lowercase:", name.lower())
Summary
In this lesson, we learned:
- What Strings are in Python.
- How to create Strings using single, double, and triple quotes.
- How to access characters using indexing.
- How to use negative indexing.
- How to find the length of a String using "len()".
- How to extract parts of a String using slicing.
- How to join Strings using concatenation.
- How to repeat Strings using the "*" operator.
- Common String methods such as "upper()", "lower()", "strip()", "replace()", and "split()".
- How to check String contents using "isdigit()", "isalpha()", and "isalnum()".
- How to use escape characters.
- How to use membership operators ("in").
- How to loop through a String.
- How to format Strings using f-strings.
- Why Strings are immutable.
Conclusion
Strings are one of the most important data types in Python because almost every program works with text data. Understanding how to create, manipulate, format, and analyze Strings is an essential skill for every Python programmer. By mastering Strings, you will be able to build applications that handle user input, process text, manage files, and communicate information effectively. In the next lesson, we will learn about String Operations and Advanced String Methods to further improve our Python programming skills.
Top comments (0)