Skip to content

Python3 Strings

Strings are the most commonly used data type in Python. We can use quotes ( ’ or “ ) to create strings.

Creating a string is simple — just assign a value to a variable. For example:

var1 = 'Hello World!'
var2 = "Runoob"

Python does not support a single character type; a single character is also treated as a string in Python.

Python uses square brackets [] to access substrings. The syntax for slicing a string is as follows:

variable[start_index:end_index]

The index starts at 0, and -1 represents the position from the end.

Example:

#!/usr/bin/python3
 
var1 = 'Hello World!'
var2 = "Runoob"
 
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])

Output of the above example:

var1[0]:  H
var2[1:5]:  unoo

You can slice a portion of a string and concatenate it with other strings, as shown in the example below:

#!/usr/bin/python3
 
var1 = 'Hello World!'
 
print ("Updated String : ", var1[:6] + 'Runoob!')

Output of the above example:

Updated String :  Hello Runoob!

When you need to use special characters in a string, Python uses the backslash \ to escape them. The table below shows all escape characters:

Escape Character Description Example
\(at end of line) Line continuation
>>> print("line1 \
... line2 \
... line3")
line1 line2 line3
>>> 
\\ Backslash
>>> print("\\")
\
\' Single quote
>>> print('\'')
'
\" Double quote
>>> print("\"")
"
\a Bell
>>> print("\a")
After execution, the computer makes a sound.
\b Backspace
>>> print("Hello \b World!")
Hello World!
\000 Null
>>> print("\000")

>>> 
\n Newline
>>> print("\n")


>>>
\v Vertical tab
>>> print("Hello \v World!")
Hello 
       World!
>>>
\t Horizontal tab
>>> print("Hello \t World!")
Hello      World!
>>>
\r Carriage return. Moves the content after \r to the beginning of the string, replacing characters one by one until the content after \r is fully replaced.
>>> print("Hello\rWorld!")
World!
>>> print('google runoob taobao\r123456')
123456 runoob taobao
\f Form feed
>>> print("Hello \f World!")
Hello 
       World!
>>> 
\yyy Octal value, y represents characters from 0~7, e.g., \012 represents newline.
>>> print("\110\145\154\154\157\40\127\157\162\154\144\41")
Hello World!
\xyy Hexadecimal value, starting with \x, y represents the characters, e.g., \x0a represents newline
>>> print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21")
Hello World!
\other Other characters are output in their normal format

Using \r to implement a percentage progress bar:

import time

for i in range(101):
    bar = '[' + '=' * (i // 2) + ' ' * (50 - i // 2) + ']'
    print(f"\r{bar} {i:3}%", end='', flush=True)
    time.sleep(0.05)
print()

The following example demonstrates the effects of different escape characters, including single quotes, newlines, tabs, backspace, form feed, ASCII, binary, octal, and hexadecimal values:

print('\'Hello, world!\'')  # Output: 'Hello, world!'

print("Hello, world!\nHow are you?")  # Output: Hello, world!
                                        #       How are you?

print("Hello, world!\tHow are you?")  # Output: Hello, world!    How are you?

print("Hello,\b world!")  # Output: Hello world!

print("Hello,\f world!")  # Output:
                           # Hello,
                           #  world!

print("The ASCII value of A is:", ord('A'))  # Output: The ASCII value of A is: 65

print("\x41 is the ASCII code of A")  # Output: A is the ASCII code of A

decimal_number = 42
binary_number = bin(decimal_number)  # Decimal to binary
print('Converted to binary:', binary_number)  # Converted to binary: 0b101010

octal_number = oct(decimal_number)  # Decimal to octal
print('Converted to octal:', octal_number)  # Converted to octal: 0o52

hexadecimal_number = hex(decimal_number)  # Decimal to hexadecimal
print('Converted to hexadecimal:', hexadecimal_number) # Converted to hexadecimal: 0x2a

In the table below, variable a has the value “Hello” and variable b has the value “Python”:

Operator Description Example
+ String concatenation a + b output: HelloPython
* Repeat string a*2 output: HelloHello
[] Access characters in string by index a[1] output e
[ : ] Slice a portion of the string, following the left-closed right-open principle. str[0:2] does not include the 3rd character. a[1:4] output ell
in Membership operator - returns True if the string contains the given character 'H' in a output True
not in Membership operator - returns True if the string does not contain the given character 'M' not in a output True
r/R Raw string - all characters are used literally without escape processing. A raw string is almost identical to a normal string except that the letter r (case-insensitive) is placed before the first quote.
print( r'\n' )
print( R'\n' )
% Format string See the next section.
#!/usr/bin/python3
 
a = "Hello"
b = "Python"
 
print("a + b output:", a + b)
print("a * 2 output:", a * 2)
print("a[1] output:", a[1])
print("a[1:4] output:", a[1:4])
 
if( "H" in a) :
    print("H is in variable a")
else :
    print("H is not in variable a")
 
if( "M" not in a) :
    print("M is not in variable a")
else :
    print("M is in variable a")
 
print (r'\n')
print (R'\n')

Output of the above example:

a + b output: HelloPython
a * 2 output: HelloHello
a[1] output: e
a[1:4] output: ell
H is in variable a
M is not in variable a
\n
\n

Python supports formatted string output. Although this may involve very complex expressions, the most basic usage is to insert a value into a string with the format specifier %s.

In Python, string formatting uses the same syntax as the C sprintf function.

#!/usr/bin/python3
 
print ("My name is %s and I am %d years old!" % ('Xiao Ming', 10))

Output of the above example:

My name is Xiao Ming and I am 10 years old!

Python string formatting symbols:

Symbol

Description

  %c

Format character and its ASCII code

  %s

Format string

  %d

Format integer

  %u

Format unsigned integer

  %o

Format unsigned octal number

  %x

Format unsigned hexadecimal number

  %X

Format unsigned hexadecimal number (uppercase)

  %f

Format floating point number, can specify precision after decimal point

  %e

Format floating point number in scientific notation

  %E

Same as %e, format floating point number in scientific notation

  %g

Shorthand for %f and %e

  %G

Shorthand for %f and %E

  %p

Format variable address as hexadecimal number

Formatting operator auxiliary directives:

Symbol Function
* Define width or decimal precision
- Left-align
+ Display plus sign (+) before positive numbers
<sp> Display a space before positive numbers
# Display zero (‘0’) before octal numbers, and ‘0x’ or ‘0X’ before hexadecimal
0 Pad displayed numbers with ‘0’ instead of spaces
% ‘%%’ outputs a single ‘%’
(var) Map variable (dictionary argument)
m.n. m is the minimum total width, n is the number of digits after the decimal point

Starting from Python 2.6, a new string formatting function str.format() was added, which enhances string formatting capabilities.


Python triple quotes allow a string to span multiple lines, and the string can contain newlines, tabs, and other special characters. Example:

#!/usr/bin/python3
 
para_str = """This is an example of a multi-line string
Multi-line strings can use tabs
TAB ( \t ).
Newlines [ \n ] can also be used.
"""
print (para_str)

Output of the above example:

This is an example of a multi-line string
Multi-line strings can use tabs
TAB (    ).
Newlines [ 
 ] can also be used.

Triple quotes free programmers from the quagmire of quotes and special characters, maintaining a small block of string format in what is known as WYSIWYG (What You See Is What You Get) format.

A typical use case is when you need a block of HTML or SQL, where string concatenation and special character escaping would be very tedious.

errHTML = '''
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
'''
cursor.execute('''
CREATE TABLE users (  
login VARCHAR(8), 
uid INTEGER,
prid INTEGER)
''')

f-string was added in Python 3.6 and later, known as literal formatted strings, and is a new syntax for string formatting.

Previously, we were used to using the percent sign (%):

>>> name = 'Runoob'
>>> 'Hello %s' % name
'Hello Runoob' 

f-string formatted strings start with f, followed by the string, with expressions enclosed in curly braces {}. It replaces variables or computed expressions with their values. Example:

>>> name = 'Runoob'
>>> f'Hello {name}'  # Replace variable
'Hello Runoob'
>>> f'{1+2}'         # Use expression
'3'

>>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'

This approach is clearly simpler — no need to decide whether to use %s or %d.

In Python 3.8, you can use the = symbol to concatenate the expression and its result:

>>> x = 1
>>> print(f'{x+1}')   # Python 3.6
2

>>> x = 1
>>> print(f'{x+1=}')   # Python 3.8
x+1=2

In Python 2, normal strings were stored as 8-bit ASCII, while Unicode strings were stored as 16-bit unicode strings, allowing representation of a wider character set. The syntax was to prefix the string with u.

In Python 3, all strings are Unicode strings.


Commonly used built-in string methods in Python:

No. Method & Description
1

capitalize()
Converts the first character of the string to uppercase

2

center(width, fillchar)

Returns a string centered in a specified width, with fillchar as the padding character (default is space).
3

count(str, beg= 0,end=len(string))


Returns the number of occurrences of str in the string. If beg or end is specified, returns the count within the specified range.
4

bytes.decode(encoding="utf-8", errors="strict")


Python 3 does not have a decode method, but we can use the decode() method of the bytes object to decode a given bytes object, which can be encoded and returned by str.encode().
5

encode(encoding='UTF-8',errors='strict')


Encodes the string in the encoding format specified by encoding. Raises a ValueError by default on error, unless errors is specified as 'ignore' or 'replace'.
6

endswith(suffix, beg=0, end=len(string))
Checks if the string ends with suffix. If beg or end is specified, checks within the specified range. Returns True if so, otherwise False.

7

expandtabs(tabsize=8)


Converts tab characters in the string to spaces. The default number of spaces for a tab is 8.
8

find(str, beg=0, end=len(string))


Checks if str is contained in the string. If the range beg and end is specified, checks within the specified range. Returns the starting index if found, otherwise returns -1.
9

index(str, beg=0, end=len(string))


Same as find(), but raises an exception if str is not found in the string.
10

isalnum()


Checks if the string consists of letters and digits, i.e., all characters in the string are letters or digits. Returns True if the string has at least one character and all characters are letters or digits; otherwise returns False.
11

isalpha()


Returns True if the string has at least one character and all characters are letters or Chinese characters; otherwise returns False.
12

isdigit()


Returns True if the string contains only digits; otherwise returns False.
13

islower()


Returns True if the string contains at least one case-sensitive character and all such characters are lowercase; otherwise returns False.
14

isnumeric()


Returns True if the string contains only numeric characters; otherwise returns False.
15

isspace()


Returns True if the string contains only whitespace; otherwise returns False.
16

istitle()


Returns True if the string is titlecased (see title()); otherwise returns False.
17

isupper()


Returns True if the string contains at least one case-sensitive character and all such characters are uppercase; otherwise returns False.
18

join(seq)


Joins all elements in seq (their string representations) into a new string using the specified string as a separator.
19

len(string)


Returns the length of the string.
20

ljust(width[, fillchar])


Returns a left-aligned string of length width, padded with fillchar (default space).
21

lower()


Converts all uppercase characters in the string to lowercase.
22

lstrip()


Removes leading spaces or specified characters from the string.
23

maketrans()


Creates a translation table for character mapping. In the simplest two-argument invocation, the first argument is the string of characters to convert, and the second argument is the string of target characters.
24

max(str)


Returns the character with the maximum value in string str.
25

min(str)


Returns the character with the minimum value in string str.
26

replace(old, new [, max])


Replaces old with new in the string. If max is specified, replaces at most max occurrences.
27

rfind(str, beg=0,end=len(string))


Similar to find(), but searches from the right.
28

rindex( str, beg=0, end=len(string))


Similar to index(), but searches from the right.
29

rjust(width,[, fillchar])


Returns a right-aligned string of length width, padded with fillchar (default space).
30

rstrip()


Removes trailing spaces or specified characters from the string.
31

split(str="", num=string.count(str))


Splits the string using str as the delimiter. If num is specified, only num+1 substrings are split.
32

splitlines([keepends])


Splits by line breaks ('\r', '\r\n', '\n'), returning a list of lines as elements. If keepends is False, line breaks are not included; if True, they are preserved.
33

startswith(substr, beg=0,end=len(string))


Checks if the string starts with the specified substring substr. Returns True if so, otherwise False. If beg and end are specified, checks within the specified range.
34

strip([chars])


Performs both lstrip() and rstrip() on the string.
35

swapcase()


Converts uppercase to lowercase and lowercase to uppercase in the string.
36

title()


Returns a "titlecased" string, where all words start with uppercase and the remaining letters are lowercase (see istitle()).
37

translate(table, deletechars="")


Translates characters in the string according to the table (containing 256 characters). Characters to be filtered out are placed in the deletechars parameter.
38

upper()


Converts lowercase letters in the string to uppercase.
39

zfill (width)


Returns a string of length width, right-aligned, with leading zeros.
40

isdecimal()


Checks if the string contains only decimal characters. Returns true if so, otherwise false.