Python Strings



What is String in Python?

A string is a sequence of characters. You can use either single or double quotation marks to surround string in Python.

'hello world' is the same as "hello world".

A character is just a symbol. For instance, the English language has 26 characters.

Computers do not deal with characters but only numbers (binary). But you can still see characters on your screen because characters are stored and manipulated as a combination of 0 and 1.

The conversion of characters to numbers is called encoding, and the reverse process is decoding. The popular encodings are ASCII and Unicode.

Python uses Unicode characters that include every character in all languages.


Assign String to a Variable

To assign a string to a variable, you can use the variable name followed by an equal sign, and the specified string.

In the following example, we will assign the string "python" to the variable x.

x = "Python"

print(x)

Output

Python

Multiline Strings

You can use the three quotes """ """ to assign a multiline string to a variable.

In the following example, we will use three double-quotes.

x = """The first line
the second line
and the third line. """

print(x)

Output

The first line 
the second line 
and the third line. 

You can also use three single quotes.

x = '''The first line
the second line
and the third line. '''

print(x)

Output

The first line 
the second line 
and the third line.

Strings are Arrays

Like many other programming languages, strings in Python are arrays of bytes representing Unicode characters.

Python does not have a character data type, but you can represent a single character by a string with a length of 1.

To access elements of the string, use square brackets [].

In the following example, we will get the character at position 3.

x = "python"

print(x[3])

Output

h

Looping Through a String

Strings are arrays, so you can loop through the characters in a string using a for loop.

In the following example, we will loop through the letters in the word "hello".

for x in "hello":
    print(x)

Output

h
e
l
l
o

String Length

You can use the len() function to determine the length of a string.

x = "learning python"

print(len(x))

Output

15

Checking String

If you want to check if a phrase or a character is present in a string, you can use the keyword in.

In the following example, we will check if "world" is present in the following text.

x = "Hello from python world."

if "world" in x:
    print("'world' is present.")

Output

'world' is present.

You can also check if a phrase or character does not exist in a string using the keyword not in.

In the following example, we will check if "hi" is not present in the following text.

x = "Hello from python world."

if "hi" not in x:
    print("'hi' is not present.")

Output

'hi' is not present.

Slicing Strings

There are different ways that you can use to slice strings in Python.


Slicing using interval

You can return a range of characters by indicating where a range starts and ends using the slicing operator : (colon).

In the following example, we will get the characters from positions 3 to 6 (not included).

x = "python is awesome"

print(x[3:8])

Output

hon i

Slicing From the Start

If you want to start the range from the first character, you can leave blink the starting index.

In the following example, we will start characters from the start to position 9 (not included).

x = "python is awesome"

print(x[:9])

Output

python is

Slicing To the End

When leaving blink the ending index, the range will go to the end.

In the following example, we will get the characters from position 7 to the end.

x = "python is awesome"

print(x[7:])

Output

is awesome

Negative Indexing

You can use negative indexes to start slicing from the end of the string.

In the following example, we will get the characters from position -6 ('w') to position -2 ('m') but not included.

x = "awesome"

print(x[-6:-2])

Output

weso

The following illustration shows the index and the negative of a string:

String indexing in Python

Modify Strings

Python offers different built-in methods that you can use on strings.


Lower case

The lower() method returns the string in lower case.

In the following example, we will use the lower() method to return a lower case of the "Python" string.

x = "Python"

print(x.lower())

Output

python

Uper case

The upper() method returns the string in the upper case.

In the following example, we will use the upper() method to return an upper case of the "Python" string.

x = "python"

print(x.upper())

Output

PYTHON

Remove Whitespace

You can use the strip() method to remove the whitespace before and/or after the specified text.

In the following example, we will use the strip() method to removes any whitespace from the beginning and the end.

x = "   Python is awesome  "

print(x.strip())

Output

Python is awesome

Replace String

You can replace a string with another string by using the replace() method.

In the following example, we will use the replace() method to replace "awesome" with "great".

x = "Python is awesome"

print(x.replace("awesome", "great"))

Output

Python is great

Split String

To split a string, you can use the split() method that returns a list where the text between the specified separator becomes the list items.

In the following example, we will use the split() method to split the strings into substrings when it finds instances of the separator.

x = "kiwi, apple, blueberry, dragonfruit"

print(x.split(","))

Output

['kiwi', ' apple', ' blueberry', ' dragonfruit']

String Concatenation

To concatenate or combine two or more strings, you can use the + operator.

In the following example, we will concatenate x with y.

x = "Python"
y = "is great"
print(x + y)

Output

Pythonis great

If you want to add space between the content of two variables, you can add a space" ".

x = "Python"
y = "is great"
print(x + " " + y)

Output

Python is great

String Format

In Python, you cannot combine strings and numbers like the following.

age = 23

# It will raise an error 
txt = "I am " + age + " years old." 

print(txt)

Output

TypeError                                 Traceback (most recent call last)

----> 3 txt = "I am " + age + " years old."

TypeError: can only concatenate str (not "int") to str

However, you can use the format() method to combine strings and numbers.

The format() method takes the passed arguments, formats them, and finally replaces the placeholders {} with the given arguments in the text.

In the following example, we will use the format() method to insert numbers into strings.

age = 23

txt = "I am {} years old." 

print(txt.format(age))

Output

I am 23 years old.

The format() method can take an unlimited number of arguments.

a = 12
b = 7
c = 3
txt = "The first number is {}, the second is {}, and the last is {}"
print(txt.format(a, b, c))

Output

The first number is 12, the second is 7, and the last is 3

With the format() method, you can use the index numbers {0} to ensure the arguments are placed in the correct placeholders.

a = 12
b = 7
c = 3
txt = "The first number is {2}, the second is {1}, and the last is {0}"
print(txt.format(a, b, c))

Output

The first number is 3, the second is 7, and the last is 12

Escape Character

In Python, some characters are not allowed in a string, so you use an escape character to use them.

An escape character is a backslash \ followed by the character you want to add.

In the following example, we will use an illegal character, a double quote inside a string surrounded by double quotes.

# It will raise an error
txt = "Hello, my name is "Michael" "

Output

txt = "Hello, my name is "Michael" "  
                             ^ 
SyntaxError: invalid syntax

To insert the illegal character, you can escape the character \"?

txt = "Hello, my name is \"Michael\" "

print(txt)

Output

Hello, my name is "Michael" 

In the below table, we will show other escape characters that can be used in Python.

+-----------+-----------------+
| Character | Result          |
+-----------+-----------------+
| \'        | Single quote    |
| \"        | Double quote    |
| \\        | Backslash       |
| \n        | New line        |
| \t        | Tab             |
| \r        | Carriage return |
| \f        | Form feed       |
| \b        | Backspace       |
| \ooo      | Octal value     |
| \xhh      | Hex value       |
+-----------+-----------------+


String Methods

Python provides different built-in methods that you can use on strings.

Method Description
capitalize() It is used to convert the first character to upper case
casefold() It is used to convert a string into lower case
center() It is used to return a centered string
count() It is used to return the number of times a specified value occurs in a string
encode() It is used to return an encoded version of the string
endswith() It is used to return True if the string ends with the specified value
expandtabs() It is used to set the tab size of the string
find() It is used to search the string for a specified value and return the position of where it was found
format() It is used to format specified values in a string
format_map() It is used to format specified values in a string
index() It is used to search the string for a specified value and returns the position of where it was found
isalnum() It is used to return True if all characters in the string are alphanumeric
isalpha() It is used to return True if all characters in the string are in the alphabet
isdecimal() It is used to return True if all characters in the string are decimal
isdigit() It is used to return True if all characters in the string are digits
isidentifier() It is used to return True if the string is an identifier
islower() It is used to return True if all characters in the string are lower case
isnumeric() It is used to return True if all characters in the string are numeric
isprintable() It is used to return True if all characters in the string are printable
isspace() It is used to return True if all characters in the string are whitespaces
istitle() It is used to return True if the string follows the rules of a title
isupper() It is used to return True if all characters in the string are upper case
join() It is used to join the elements of an iterable to the end of the string
ljust() It is used to return a left justified version of the string
lower() It is used to convert a string into lower case
lstrip() It is used to return a left trim version of the string
maketrans() It is used to return a translation table to be used in translations
partition() It is used to return a tuple where the string is parted into three parts
replace() It is used to return a string where a specified value is replaced with a specified value
rfind() It is used to search the string for a specified value and returns the last position of where it was found
rindex() It is used to search the string for a specified value and returns the last position of where it was found
rjust() It is used to return a right justified version of the string
rpartition() It is used to return a tuple where the string is parted into three parts
rsplit() It is used to split the string at the specified separator and returns a list
rstrip() It is used to return a right trim version of the string
split() It is used to split the string at the specified separator and returns a list
splitlines() It is used to split the string at line breaks and returns a list
startswith() It is used to return True if the string starts with the specified value
strip() It is used to return a trimmed version of the string
swapcase() It is used to swap cases, the lower case becomes the upper case and vice versa
title() It is used to convert the first character of each word to upper case
translate() It is used to return a translated string
upper() It is used to convert a string into upper case
zfill() It is used to fill the string with a specified number of 0 values at the beginning


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.