Python Strings - Jupyter Notebook
Python Strings - Jupyter Notebook
Manipulation
Objectives:
Work with Strings
Perform basic string operations
Manipulate strings using indexing and slicing
In Python, a string represents a series of characters. A string can be defined using single ( ' )
or double ( " ) quotes. For example:
Strings can also contain spaces, digits, and even special characters:
Out[2]: '@#2_#]&*^%$'
Printing Strings
Hello, world!
Michael Jackson
Indexing
Strings in Python are zero-indexed, meaning the first character has an index of 0 , the second
has an index of 1 , and so on.
[Tip]: Because indexing starts at 0, it means the first index is on the index 0.
M
l
o
Negative Indexing
You can also use negative indices to access characters from the end of the string:
n
M
15
String Slicing
Slicing allows you to extract a substring from a string using the syntax str[start:end] .
In [8]: # Slice from index 0 to index 3 (not inclusive)
print(name[0:4]) # Output: 'Mich'
# Slice from index 8 to index 11
print(name[8:12]) # Output: 'Jack'
Mich
Jack
String Stride
Stride allows you to skip characters during slicing. The syntax is str[start:end:stride] .
McalJcsn
Mca
Reversing a String
noskcaJ leahciM
String Concatenation and Replication
You can concatenate strings using the + operator:
String Methods
Python provides a variety of string methods to manipulate strings. Below are a few commonly
used methods:
replace()
find()
Find the index of the first occurrence of a substring. Returns -1 if the substring is not found:
5
8
True
True
True
True
True
True
True
Splitting Strings
In [18]: text = 'Python is a fun programming language'
print(text.split(' '))
# Output: ['Python', 'is', 'a', 'fun', 'programming', 'language']
Summary
In this notebook, we covered:
These concepts are fundamental for working with text data in Python.