Strings in Python: Understanding and Working with Text (Part 1)
Strings are one of the most commonly used data types in Python. They allow us to work with text such as names, messages, sentences, labels, and other textual information.
A string is represented using quotation marks. Python allows strings to be written using either single quotes or double quotes.
For example:
name = "Riya"
city = 'Pune'
course = "Python"All three values are strings.
A string can contain letters, numbers, spaces, and special characters.
message = "Welcome to Python"
code = "DS2026"
symbol = "@"Creating Strings
There are several ways to create strings in Python, but the most common approach is to place text inside single or double quotation marks.
Using Single Quotes
language = 'Python'Using Double Quotes
language = "Python"Both create a string containing the same text.
We can check the data type using type():
language = "Python"
print(type(language))Output:
<class 'str'>The str in the output indicates that the value is a string.
Strings Are Made Up of Characters
A string is a sequence of individual characters.
Consider:
word = "Python"The string contains the following characters:
P y t h o nEach character occupies a position within the string.
Python allows us to access these individual characters using their index.
This is called string indexing.
String Indexing
Indexing is the process of accessing an individual character from a string using its position.
Python uses zero-based indexing.
This means that the first character has index 0, the second character has index 1, and so on.
For example:
word = "Python"The positions are:
P y t h o n
0 1 2 3 4 5To access a character, we place the index inside square brackets:
word[0]Output:
PSimilarly:
word[3]Output:
hThe index tells Python which character we want to access.
Positive Indexing
When we count positions from the beginning of a string, we use positive indexing.
For example:
text = "Python"The positive indexes are:
P y t h o n
0 1 2 3 4 5Therefore:
print(text[0])
print(text[2])
print(text[5])Output:
P
t
nPositive indexing starts from 0 and moves from left to right.
Negative Indexing
Python also allows us to access characters from the end of a string using negative indexes.
Negative indexing starts with -1 for the last character.
For example:
text = "Python"The positions can be represented as:
P y t h o n
-6 -5 -4 -3 -2 -1Therefore:
print(text[-1])Output:
nAnd:
print(text[-3])Output:
hNegative indexing is particularly useful when we want to access characters from the end of a string without first calculating its length.
Accessing Characters from a String
Using indexing, we can access any valid position in a string.
For example:
course = "Data Science"
print(course[0])
print(course[5])
print(course[-1])Output:
D
S
eHere:
course[0]accesses the first character.course[5]accesses the character at index5.course[-1]accesses the last character.
The same indexing principle works for strings regardless of their length.
String Slicing
In Python, indexing allows us to access an individual character from a string. But what if we want to extract a group of characters instead of just one?
This is where string slicing is useful.
String slicing allows us to extract a specific portion of a string by specifying its starting and ending positions.
The syntax is:
string[start:end]Here:
startspecifies the index from which slicing begins.endspecifies the index where slicing stops.- The ending index is exclusive, which means the character at that position is not included.
For example:
text = "Hello World"
print(text[0:5])Output:
HelloHere, slicing starts at index 0 and stops before index 5. Therefore, only the characters from index 0 to 4 are included.
Specifying Start and End Positions
We can extract different portions of a string by changing the start and end positions.
text = "I am a good student"
print(text[0:4])
print(text[5:11])Output:
I am
a goodThe first statement extracts characters from index 0 to 3, while the second extracts characters from index 5 to 10.
Omitting Start and End Positions
Python also allows us to omit the starting or ending position.
If the starting position is omitted, slicing begins from the first character.
text = "Hello World"
print(text[:5])Output:
HelloIf the ending position is omitted, slicing continues until the end of the string.
print(text[6:])Output:
WorldUsing Step in String Slicing
Python also allows us to specify a step value in slicing.
The syntax is:
string[start:end:step]The step determines how many positions Python moves forward while extracting characters.
For example:
text = "Hello World"
print(text[0:5:1])
print(text[0:5:2])Output:
Hello
HloIn the first example, the step is 1, so Python selects every character.
In the second example, the step is 2, so Python selects every second character.
If no step is specified, Python uses 1 by default.
Negative Slicing
Python also allows us to use negative indexes while slicing strings.
Get Mrunal Shrikumar’s stories in your inbox
Join Medium for free to get updates from this writer.
For example:
text = "Hello World"
print(text[-3:])Output:
rldHere, -3 identifies the third character from the end of the string. Slicing begins at that position and continues to the end of the string.
Similarly:
print(text[:-3])Output:
Hello WoThis extracts the string up to, but not including, the last three characters.
Reversing a String Using Slicing
We can also reverse a string using a negative step value.
text = "Hello World"
print(text[::-1])Output:
dlroW olleHHere, [::-1] tells Python to move through the string in reverse order, starting from the end.
String slicing is useful when we want to extract specific portions of text, access characters from the end, or reverse a string.
What Happens with an Invalid Index?
An index must correspond to an existing position in the string.
For example:
word = "Python"
print(word[10])The string does not have a character at index 10.
Python therefore raises an error:
IndexError: string index out of rangeThis happens because the requested index is outside the valid range of the string.
Understanding valid indexes is therefore important when accessing individual characters.
Strings Are Immutable
One of the important properties of strings in Python is that they are immutable.
Immutable means that once a string has been created, its individual characters cannot be changed directly.
For example:
word = "Python"Suppose we try to change the first character:
word[0] = "J"Python will raise a TypeError because strings do not support changing individual characters through indexing.
Output:
TypeError: 'str' object does not support item assignmentThis happens because strings are immutable, meaning their individual characters cannot be changed after the string has been created.
The important distinction is that we can assign a completely new string to the variable:
word = "Python"
word = "Java"
print(word)Output:
JavaHere, the variable word is reassigned to a different string. The original string itself was not modified character by character.
This is what makes strings immutable in Python.
Finding Out Whether Text Exists in a String
Python also allows us to check whether a particular character or sequence of characters exists inside a string.
The in operator can be used for this purpose.
For example:
message = "Welcome to Python"
print("Python" in message)Output:
TruePython found "Python" inside the string.
We can also check for a character:
message = "Welcome to Python"
print("W" in message)Output:
TrueIf the specified text is not present, the result is False:
print("Java" in message)Output:
FalseUsing not in
The not in operator checks whether a character or sequence of characters does not exist in a string.
For example:
message = "Welcome to Python"
print("Java" not in message)Output:
TrueBecause "Java" is not present in the string, the expression evaluates to True.
Similarly:
print("Python" not in message)Output:
FalseBecause "Python" is present in the string.
A Practical Example
Let’s put some of these concepts together.
student_name = "Kavya"
print(student_name[0])
print(student_name[-1])
print("v" in student_name)
print("z" in student_name)Output:
K
a
True
FalseHere:
student_name[0]accesses the first character.student_name[-1]accesses the last character."v" in student_namechecks whethervexists in the string."z" in student_namechecks whetherzexists in the string.
This shows how Python allows us to work with individual characters as well as search within a string.
Strings and Their Length
Python provides the built-in len() function to determine the number of characters in a string.
For example:
word = "Python"
print(len(word))Output:
6The length includes every character in the string.
Spaces are also characters.
For example:
message = "Hello World"
print(len(message))Output:
11The space between "Hello" and "World" is included in the count.
The length of a string is also useful when understanding its valid index positions.
For a string of length 6, the positive indexes range from 0 to 5, while the negative indexes range from -1 to -6.
Strings and Numbers Are Different
It is important not to confuse a numerical value with a string containing a number.
Consider:
a = 50
b = "50"The first value is an integer:
print(type(a))Output:
<class 'int'>The second value is a string:
print(type(b))Output:
<class 'str'>They may look similar when displayed, but Python treats them differently.
This distinction becomes especially important when performing operations or working with user input.
Key Takeaways
Strings are used to represent text in Python.
The important concepts covered in this article are:
- Strings are written using single or double quotation marks.
- A string is a sequence of characters.
- Python uses zero-based indexing.
- Positive indexing accesses characters from left to right.
- Negative indexing accesses characters from right to left.
- Individual characters can be accessed using square brackets.
- String slicing allows us to extract a portion of a string.
- The ending index in slicing is exclusive.
- A negative step can be used to reverse a string.
- An invalid index produces an
IndexError. - Strings are immutable, so individual characters cannot be changed directly.
- The
inoperator checks whether text exists inside a string. - The
not inoperator checks whether text does not exist inside a string. - The
len()function returns the number of characters in a string. - A number such as
50and a string such as"50"are different data types.
Strings are an important way of working with textual information in Python. Understanding how strings are represented, accessed and sliced provides a foundation for working with text in Python programs.








