Everything You Need to Know About Python Strings

Everything You Need to Know About Python Strings

Tags
Python
Published
June 14, 2022
Author
Abod

1. What’s a string?

In plain English, a string is just a block of text, in a more technical way it’s a sequence of letters/numbers and Unicode and it’s a built-in datatype in Python.

Creating a string

To create a string in Python, you define it inside two double or single quotes
“Something like this” or ‘this works too’

Storing a string in a variable

# Quotation is different but those two are the same thing some_variable_name = "Hey this is a Python string" # OR some_variable_name = 'hey look a single quote string'

Indexing

You can get a subset of any given string (text) using the braces index.
Considering the first letter in a string to 0, you can get any single letter like this:
text = 'hey look a single quote string' print(text[0]) # -> h print(text[1]) # -> e print(text[2]) # -> y

Reverse indexing

You can also use this same way to read the values from the end of the string, -1 to get the last character, -2 to get the second last character and so on, it will look something like this.
text = 'hey look a single quote string' print(text[-1]) # -> g print(text[-2]) # -> n print(text[-3]) # -> i

Getting multiple characters

To get a subset of any given text, you specify from which letter to which letter using their index, for example to get the 5 letters you will use it like this [0:6], note that the second number denotes the up to index, and not including that index, let’s see some examples
text = 'whilelab' print(text[0:5]) # -> whil print(text[3:6]) # -> lel # Note how you can use the negative indexing to exclude the last # three letters for example. print(text[0:-3]) # -> while

Connecting two strings together

text = 'Python tutorials on' text_2 = "YouTube" full_sentence = text + text_2 # Note the + sign print(full_sentence) # -> Python tutorials on YouTube

Multiplying string by a number

greetings = "Hey!" repeated_greetings = greetings * 3 print(repeated_greetings) # -> Hey!Hey!Hey!

Getting the length of any string

Python has a magical method called len() which can be used in any array/sequence and it will return the length of it, this works with strings too
sentence = "Everything" len(sentence) # -> 10

Checking if a word in a string

You can use the ‘in’ built-in Python keyword to check if a string is part of another string
text = "Sun is directly above Earth's equator" print("directly" in text) #-> True text = "Sun is directly above Earth's equator" print("moon" in text) #-> False text = "Sun is directly above Earth's equator" print("sun" in text) #-> False, because it's case sensative text = "Sun is directly above Earth's equator" print("ab" in text) #-> True, Note how it catches the 'ab' in 'above'