Python Strings: What I Learned About Working with Text
Strings were one of the first Python concepts I came across. At first, I thought a string was just text inside quotation marks. And honestly, that's basically what it is. But once I started working with names, message
Strings were one of the first Python concepts I came across.
At first, I thought a string was just text inside quotation marks.
And honestly, that's basically what it is.
But once I started working with names, messages, passwords, and other text, I realised there was a lot more I could do with strings.
Creating a string
A string is simply text.
For example:
name = "Feddy"
message = 'Welcome to Python'
Both single and double quotation marks work.
I usually use double quotes, but the important thing is to be consistent.
Accessing characters
Just like lists, strings are indexed.
Python starts counting from 0.
For example:
name = "Feddy"
print(name[0])
The result is:
F
The second character is:
print(name[1])
which gives:
e
This was useful because I realised I could work with individual characters instead of treating the whole string as one thing.
Negative indexing
I can also count from the end.
name = "Feddy"
print(name[-1])
This gives:
y
And:
print(name[-2])
gives:
d
I found this especially useful when I wanted to get the last character without calculating the length of the string.
Slicing strings
I can also take part of a string using slicing.
For example:
name = "Feddy Mwanjumwa"
print(name[0:5])
The result is:
Feddy
The starting position is included, but the ending position is not.
I can also get everything after a certain position:
print(name[6:])
This gives:
Mwanjumwa
Once I understood slicing with lists, slicing strings felt much easier.
Changing the case
Python gives me several ways to change the case of text.
For example:
name = "feddy mwanjumwa"
print(name.upper())
This gives:
FEDDY MWANJUMWA
I can also use:
print(name.lower())
which gives:
feddy mwanjumwa
And if I want the first letter of each word capitalised:
print(name.title())
which gives:
Feddy Mwanjumwa
I found these methods useful when dealing with inconsistent text.
Removing unwanted spaces
Sometimes text has spaces that shouldn't be there.
For example:
name = " Feddy "
I can use:
print(name.strip())
The result is:
Feddy
There are also:
lstrip()
and:
rstrip()
which remove spaces from the left and right respectively.
This became particularly useful when I started thinking about cleaning data.
Replacing text
I can replace part of a string using replace().
For example:
message = "I am learning Java"
message = message.replace("Java", "Python")
Now the message becomes:
I am learning Python
This is useful when I need to correct or change specific text.
Checking whether text exists
I can check whether a word or character exists inside a string using in.
For example:
email = "[email protected]"
print("@gmail.com" in email)
The result is:
True
I can also use this in a condition:
if "@gmail.com" in email:
print("Gmail address")
This made strings much more useful when I started thinking about validation.
Finding text
I can use find() to get the position of a piece of text.
For example:
email = "[email protected]"
print(email.find("@"))
The result is:
5
So the @ is at index 5.
I can use this when I need to know where something appears inside a string.
Counting characters or words
count() tells me how many times something appears.
For example:
message = "Python is easy and Python is useful"
print(message.count("Python"))
The result is:
2
This can be useful when analysing or checking text.
Splitting a string
split() turns a string into a list.
For example:
names = "Feddy,Amina,Brian"
names = names.split(",")
Now I get:
["Feddy", "Amina", "Brian"]
This was an important one for me because it showed me how I could move from text into a list of individual values.
Joining strings
join() does almost the opposite.
Suppose I have:
names = ["Feddy", "Amina", "Brian"]
I can join them together:
result = ", ".join(names)
The result is:
Feddy, Amina, Brian
This is useful when I have separate pieces of text that I want to combine into one string.
Checking the beginning and end
I can check whether a string starts or ends with certain text.
For example:
filename = "report.pdf"
print(filename.startswith("report"))
This gives:
True
And:
print(filename.endswith(".pdf"))
also gives:
True
This can be useful when working with filenames or user input.
String formatting with f-strings
One of my favourite things about Python strings is f-strings.
They make it easy to combine text with variables.
For example:
name = "Feddy"
age = 20
print(f"My name is {name} and I am {age} years old.")
The result is:
My name is Feddy and I am 20 years old.
I found this much cleaner than constantly joining strings together with +.
A practical example
I can put several string concepts together in a simple program.
Suppose a user enters their name with extra spaces and strange capitalisation:
name = input("Enter your name: ")
I can clean it:
name = name.strip().title()
Then display it:
print(f"Welcome, {name}!")
So if the user enters:
fEDDY mwanjumwa
the program displays:
Welcome, Feddy Mwanjumwa!
This was the kind of example that helped me understand why string methods actually matter.
What I understood
The biggest thing I learnt is that strings aren't just text that I print on the screen.
I can clean them, search them, split them, combine them, change their case, check them, and extract specific parts from them.
The methods I started using most are:
strip() ā remove unwanted spaces
upper() ā convert to uppercase
lower() ā convert to lowercase
title() ā capitalise words
replace() ā replace text
split() ā turn text into a list
join() ā combine text
find() ā find the position of text
count() ā count occurrences
Final thoughts
Strings seemed very basic when I first started Python.
But once I started working with real text, I realised how often I needed to manipulate it.
For me, strings really started making sense when I stopped thinking of them as just words inside quotation marks and started thinking of them as data that I could work with.
That shift made a big difference in how I approached Python.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes ā full credit and traffic to the original publisher.