Strings (9/100 Days of Python)
In Python, a string is a sequence of characters. Strings are used to store text and can be created using either single quotes (‘) or double quotes (“). We’ve already worked with strings in print()
and input()
statements. They can be created and stored in variables as well:
hello = "Hello, World!"
s = 'This is a string'
You can use the len
function to get the length of a string, which is the number of characters it contains:
s = 'Hello, World!'
length = len(s) # length is 12
print(length, len(s)) # prints 12 12
Accessing Characters in a String
You can access individual characters in a string using indexes. In Python, indexing starts at 0, so the first character in a string is at index 0, the second character is at index 1, and so on:
s = "Hello, World!"
# Get the first character
first_char = s[0] # first_char is 'H'
# Get the last character
last_char = s[-1] # last_char is '!'
Note that accessing the elements from the end starts from -1, the one before is -2, and so on, while elements from the start begin the indexing from 0, then 1, and so on.
Slicing
You can also use indexing to slice a string and get a substring. To do this, you use the [start:end]
syntax, where start
is the index of the first character you want to include and end
is the index of the character you want to stop at (but not include).
Here’s an example of how to slice a string:
s = 'Hello, World!'
# Get the first five characters
substring = s[0:5] # substring is 'Hello'
# Get all characters except the first and last
substring = s[1:-1] # substring is 'ello, World'
Modifying Strings
In Python, strings are not mutable. This means that you cannot directly change the value of a string. You can modify a string by creating a new one and assigning a new value to it, or by using string methods to manipulate its contents:
s = 'Hello, World!'
# Concatenate two strings (will print Hello, World! Nice meeting you!)
print(s + ' Nice meeting you!')
# Replace a character
s[0] = 'h' # This will produce an error as strings are immutable
# Concatenate two strings
s += 'How are you?' # s is now "Hello, World! How are you?"
# Make a string uppercase
s = s.upper() # s is now "HELLO, WORLD! HOW ARE YOU?"
# Make a string lowercase
s = s.lower() # s is now "hello, world! how are you?"
# Split a string into a list of words
words = s.split() # words is ['hello,', 'world!', 'how', 'are', 'you?']
There are many other string methods available in Python, such as replace
, strip
, find
, index
, and format
. You can find a complete list of string methods in the Python documentation.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — strings
- Full series: 100 Days of Python
- Previous topic: Augmented assignments (+=, -=, etc.)
- Next topic: How to format text and what are f-strings in Python?