Python Strings

String literals

String literals in Python are enclosed in single or double quotes.

hello is equivalent to "hello".

You can use print() The function displays a string literal:

Example

print("Hello")
print('Hello')

Running an instance

Assigning a string to a variable

You can assign a string to a variable by using the variable name followed by an equal sign and a string:

Example

a = "Hello"
print(a)

Running an instance

Multi-line strings

You can use three quotes to assign multi-line strings to variables:

Example

You can use three double quotes:

a = """Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code.
print(a)

Running an instance

Or three single quotes:

Example

a = '''Python is a widely used general-purpose, high level programming language. 
It was initially designed by Guido van Rossum in 1991 
and developed by Python Software Foundation. 
It was mainly developed for emphasis on code readability, 
and its syntax allows programmers to express concepts in fewer lines of code.
print(a)

Running an instance

Note:In the result, the newline character is inserted at the same position as in the code.

Strings are arrays

Like many other popular programming languages, strings in Python are byte arrays representing unicode characters.

However, Python does not have a character data type; a single character is a string of length 1.

Brackets can be used to access elements of a string.

Example

Get the character at position 1 (remember that the position of the first character is 0):

a = "Hello, World!"
print(a[1])

Running an instance

Slicing

You can use slicing syntax to return a range of characters.

Specify the start and end indices separated by a colon to return a part of the string.

Example

Get the characters from position 2 to position 5 (excluding):

b = "Hello, World!"
print(b[2:5])

Running an instance

Negative indices

Use negative indexing to slice from the end of the string:

Example

Get the characters from position 5 to position 1, counting from the end of the string:

b = "Hello, World!"
b = "Hello, World!"

Running an instance

print(b[-5:-2])

String length

Example

To get the length of a string, please use the len() function.

a = "Hello, World!"
The len() function returns the length of a string:

Running an instance

String Methods

print(len(a))

Example

Python has a set of built-in methods for strings.

The strip() method removes whitespace characters from the beginning and end:
a = " Hello, World! "

Running an instance

Example

The strip() method removes whitespace characters from the beginning and end:

a = "Hello, World!"
The lower() method returns a string in lowercase:

Running an instance

Example

The upper() method returns a string in uppercase:

a = "Hello, World!"
print(a.upper())

Running an instance

Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("World", "Kitty"))

Running an instance

Example

The split() method splits a string into substrings when it finds an instance of the delimiter:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Running an instance

Please use our string method reference manual to learn more about string methods.

Check string

To check if a specific phrase or character exists in a string, we can use the in or not in keywords.

Example

Check if the phrase "ina" exists in the following text:

txt = "China is a great country"
x = "ina" in txt
print(x)

Running an instance

Example

Check if the phrase "ina" does not exist in the following text:

txt = "China is a great country"
x = "ain" not in txt
print(x) 

Running an instance

String concatenation

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

Example

Merge variables a and b into variable c:

a = "Hello"
b = "World"
c = a + b
print(c)

Running an instance

Example

Add a space between them:

a = "Hello"
b = "World"
c = a + " " + b
print(c)

Running an instance

String formatting

As learned in the Python variables chapter, we cannot combine strings and numbers like this:

Example

age = 63
txt = "My name is Bill, I am " + age
print(txt)

Running an instance

But we can use format() The method combines strings and numbers!

format() The method accepts the passed parameters, formats them, and places them in placeholders {} in the string where it is located:

Example

Using format() The method inserts a number into a string:

age = 63 
txt = "My name is Bill, and I am {}"
print(txt.format(age))

Running an instance

format() Methods accept an unlimited number of parameters and place them in their respective placeholders:

Example

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

Running an instance

You can use the index number {0} To ensure that the parameters are placed in the correct placeholders:

Example

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Running an instance

String Methods

Python has a set of built-in methods that can be used on strings.

Note:All string methods return a new value. They do not change the original string.

Method Description
capitalize() Convert the first character to uppercase.
casefold() Convert the string to lowercase.
center() Return the centered string.
count() Return the number of times the specified value appears in the string.
encode() Return the encoding version of the string.
endswith() If the string ends with the specified value, return true.
expandtabs() Set the tab size of the string.
find() Search for the specified value in the string and return the position where it is found.
format() Format the specified value in the string.
format_map() Format the specified value in the string.
index() Search for the specified value in the string and return the position where it is found.
isalnum() If all characters in the string are alphanumeric, return True.
isalpha() If all characters in the string are in the alphabet, return True.
isdecimal() If all characters in the string are decimals, return True.
isdigit() If all characters in the string are digits, return True.
isidentifier() If the string is an identifier, return True.
islower() If all characters in the string are lowercase, return True.
isnumeric() If all characters in the string are numbers, return True.
isprintable() If all characters in the string are printable, return True.
isspace() If all characters in the string are whitespace characters, return True.
istitle() Return True if the string follows the title case rules.
isupper() Return True if all characters in the string are uppercase.
join() Concatenate the elements of an iterable object to the end of the string.
ljust() Return the left-aligned version of the string.
lower() Convert the string to lowercase.
lstrip() Return the left-trimmed version of the string.
maketrans() Return the translation table used in the conversion.
partition() Return a tuple where the string is divided into three parts.
replace() Return a string where the specified value is replaced with the specified value.
rfind() Search for the specified value in the string and return the last position where it is found.
rindex() Search for the specified value in the string and return the last position where it is found.
rjust() Return the right-aligned version of the string.
rpartition() Return a tuple where the string is divided into three parts.
rsplit() Split the string at the specified delimiter and return a list.
rstrip() Return the right-trimmed version of the string.
split() Split the string at the specified delimiter and return a list.
splitlines() Split the string at newline characters and return a list.
startswith() Return true if the string starts with the specified value.
strip() Return the truncated version of the string.
swapcase() Toggle case, lowercase becomes uppercase, and vice versa.
title() Convert the first character of each word to uppercase.
translate() Return the converted string.
upper() Convert the string to uppercase.
zfill() Fill the beginning of the string with a specified number of 0 values.

Note:All string methods return a new value. They do not change the original string.