Strings in Python
This blog post is part of our course Python Tutorial for Ultimate Beginners.
Strings are used in Python to record text information, such as names. Strings in Python are actually a sequence, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string “hello’ to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).
In this blog we’ll learn about the following:
- Creating Strings
- Printing Strings
- String Indexing and Slicing
- String Properties
- String Methods
Creating a String
To create a string in Python you need to use either single quotes or double-quotes. For example:
# Creating a String
# Single word
s = 'hello' print(s) # Entire phrase
phrase = 'This is also a string' print(phrase) # We can also use double quote
s2 = "String built with double quotes"
print(s2)>>> s = ' I'm using single quotes, but this will create an error' SyntaxError: invalid syntax
The above code will give you an error because of the single quote in I'm
stopped the string. You can use combinations of double and single quotes to get the complete statement.
Here is an example of single and double quotes-
>>> s = "Now I'm ready to use the single quotes inside a string!"
Printing a String
We can use a print statement to print a string.
# print statement to print a string
print('Hello World 1')
print('Hello World 2')
print('Use \n to print a new line')
print('\n') print('See what I mean?')
String Basics
We can also use a function called len()
to check the length of a string.
>>> len('Hello World')
11
Python’s built-in len()
the function counts all of the characters in the string, including spaces and punctuation.
String Indexing
We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let’s learn how this works.
In Python, we use brackets []
after an object to call its index. We should also note that indexing starts at 0
for Python.
Let’s create a new object called s and then walk through a few examples of indexing.
>>> # Assign s as a string
>>> s = 'Hello World'
>>> # Print the object
>>> print(s)
Hello World
Let’s start at indexing!
# Show first element (in this case a letter)
>>> s[0]
H
We can use a :
to perform slicing which grabs everything up to a designated point. For example:
# Grab everything past the first term all the way to the length of s which is len(s)
>>> s[1:]# Grab everything UP TO the 3rd index
>>> s[:3]
Note the above slicing. Here we’re telling Python to grab everything from 0 up to 3. It doesn’t include the 3rd index. You’ll notice this a lot in Python, where statements and are usually in the context of “up to, but not including”.
#Everything
>>> s[:]
We can also use negative indexing to go backwards.
# Last letter (one index behind 0 so it loops back around)
>>> s[-1]# Grab everything but the last letter
>>> s[:-1]
We can also use index and slice notation to grab elements of a sequence by a specified step size (the default is 1). For instance, we can use two colons in a row and then a number specifying the frequency to grab elements. For example:
# Grab everything, but go in steps size of 1
>>>s[::1] # Grab everything, but go in step sizes of 2
>>>s[::2]# We can use this to print a string backwards
>>>s[::-1]
String Properties
It’s important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changed or replaced. For example:
>>> s = 'Hello World' # Let's try to change the first letter to 'x'
>>> s[0] = 'x'
TypeError: 'str' object does not support item assignment
Notice how the error tells us directly what we can’t do, change the item assignment!
Concatenate strings
>>> s = 'Hello World' # Concatenate strings!
>>> s + ' concatenate me!'
Basic Built-in String methods
Objects in Python usually have built-in methods. These methods are functions inside the object that can perform actions or commands on the object itself. We call methods with a period and then the method name. Methods are in the form:object.method(parameters)
Where parameters are extra arguments we can pass into the method.
Here are some examples of built-in methods in strings:
# A few Basic Built-in String methods
s = "Hello World" # Upper Case a string
s.upper() # Lower case
s.lower() # Split a string by blank space (this is the default)
s.split() # Split by a specific element (doesn't include the element that was split on)
s.split('W')
There are many more methods than the ones covered here. We will cover that in the Advanced String section.
Originally published at https://blog.upendra.tech on June 3, 2020.