String is a commonly used data type in Python. It is simply a series of characters. To define a string literal in Python, you just place your characters within single quotes or double quotes.
var1 = "This is a String in Python"
var2 = 'You can also use single quotes'
You can access any character in a string with its index value. Python uses 0-based indexing, so first character in a string has index 0, second character has index 1. You can also use negative indexes to access characters at the end. For instance, to access the last character in a string, you can use index -1.
var1 = "Hello World!"
print(var1[0]) # prints H (first character)
print(var1[-1]) # prints ! (last character)
Slicing a String
To slice a string, you can use Python’s slicing operator [].
Slicing Operator
var[start:stop:step]
start: Specifies the start of the index value (Inclusive). If not given, the default value is 0.
stop: Specifies the end of the index value (Exclusive). If not given, the default value is the last element.
step: Specifies the number of steps to jump between start and stop index. If not given, the default value is 1.
var1 = "Hello World!"
print(var1[0:2]) # First two characters ("He")
print(var1[:2]) # If start index is not specified,
# default value is 0
print(var1[6:8]) # Two characters from 7th character
# (index 7th charater is 6 )
# ("Wo")
print(var1[-2:]) # Last two characters
# ("d!")
print(var1[::-1]) # Reverse the string (step = -1)
# ("!dlroW olleH")
Multiline Strings
To create a multiline string in Python, you can enclose the string in triple double quotes ("""
) or triple single quotes ('''
).
print("""Triple double quotes are used
in this example to create multi-line string.
You can also use triple single quotes.""")
String Formatting
You can format a string using format()
method. Placeholder for your data is identified with curly braces {}.
print("My name is {}!".format("Michael"))
# My name is Michael!
To access values in a formatted string, you can use index numbers (index of first value is 0, second value is 1, and so on).
print("Hello {1}. My name is {0}!".format("George", "Michael"))
# Hello Michael. My name is George!
The in Operator
In operator is used to check if a string contains a substring. It returns true if a substring exists in the main string. Otherwise, it returns false.
main_colors = "red orange yellow green blue indigo violet"
print("red" in main_colors) # True
print("brown" in main_colors) # False
Escape Characters
There are some special characters that you cannot use directly in a string. To use these special characters, you need to prepend them with a backslash (\
).
For example, to put a double quote in a string, you need to prepend it with backslash \"
.
print("Learning \"Python\" is fun")
# Learning "Python" is fun
Commonly used escape characters are:
Escape Character | Description |
---|---|
\’ | Single Quote |
\” | Double Quote |
\t | Tab |
\r | Carriage Return |
\n | Newline |
\\ | Backslash |
\b | Backspace |
Built-in String Methods
There are many useful built-in string methods in Python. Commonly used string methods are described below.
The upper()
and lower()
methods are used to convert all letters in a string to uppercase or lowercase.
print("Hello World!".upper()) # HELLO WORLD!
print("Hello World!".lower()) # hello world!
The startswith()
and endswith()
methods are used to check whether a string starts with or ends with a string. These methods return true if the string starts with (or ends with) the string specified in the parameter.
print("Hello World!".startswith("Hello")) # True
print("Hello World!".endswith("World!")) # True
The strip()
, rstrip()
, and lstrip()
methods are used to trim strings (i.e. remove whitespace characters). lstrip()
method is used to remove any whitespace character at the beginning of a string, rstrip()
method is used to remove whitespace characters at the end of a string, strip()
method is used to remove whitespace characters at both sides.
print(" Hello World! ".lstrip()) # "Hello World! "
print(" Hello World! ".rstrip()) # " HelloWorld!"
print(" Hello World! ".strip()) # "HelloWorld!"