YouTip LogoYouTip

Python Strings

Python String | Novice Tutorial

Python2.x Python String

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

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

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

Python does not have a single character type. A single character is also used as a string in Python.

To access substrings in Python, you can use square brackets to slice the string, as shown in the following example:

Example(Python 2.0+)

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

print "var1: ", var1
print "var2[1:5]: ", var2[1:5]

The execution result of the above example:

var1:  H
var2[1:5]:  ytho

Python String Concatenation

We can slice a string and concatenate it with other strings, as shown in the following example:

Example(Python 2.0+)

var1 = 'Hello World!'

print("Output :- "), var1[:6] + '!'

The execution result of the above example

Output :-  Hello !

Python Escape Characters

When special characters need to be used within a character, Python uses backslash escape characters. As shown in the table below:

Escape CharacterDescription
(at end of line)Line continuation character
\Backslash symbol
'Single quote
"Double quote
aBell
bBackspace
eEscape
00Null
nLine feed
vVertical tab
tHorizontal tab
rCarriage return
fForm feed
oyyOctal number, y represents characters from 0~7, for example: 12 represents line feed.
xyyHexadecimal number, starting with x, yy represents the character, for example: x0a represents line feed
otherOther characters are output in normal format

Python String Operators

In the following examples, variable a has the value string "Hello", and variable b has the value "Python":

OperatorDescriptionExample
+String concatenation>>>a + b 'HelloPython'
*Repeat output string>>>a * 2 'HelloHello'
[]Get character in string by index>>>a 'e'
[ : ]Slice a part of the string>>>a[1:4] 'ell'
inMembership operator - Returns True if the given character is contained in the string>>>"H" in a True
not inMembership operator - Returns True if the given character is not contained in the string>>>"M" not in a True
r/RRaw string - Raw strings: All strings are used literally, without interpreting escape special or non-printable characters. Raw strings have almost exactly the same syntax as ordinary strings, except they are prefixed with the letter "r" (can be uppercase) before the first quote of the string.>>>print r'n' n >>>>print R'n' n
%Format stringSee next section

Example(Python 2.0+)

a = "Hello"
b = "Python"

print "a + b output result: ", a + b
print "a * 2 output result: ", a * 2
print "a output result: ", a
print "a[1:4] output result: ", 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'

The execution result of the above program is:

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

Python String Formatting

Python supports formatted string output. Although very complex expressions can be used, the most basic usage is to insert a value into a string containing the string format specifier %s.

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

As shown in the following example:

#!/usr/bin/python

print("My name is %s and weight is %d kg!") % ('Zara', 21)

The output result of the above example:

My name is Zara and weight is 21 kg!

Python string formatting symbols:

SymbolDescription
%cFormat character and its ASCII code
%sFormat string
%dFormat integer
%uFormat unsigned integer
%oFormat unsigned octal number
%xFormat unsigned hexadecimal number
%XFormat unsigned hexadecimal number (uppercase)
%fFormat floating point number, precision after decimal point can be specified
%eFormat floating point number using scientific notation
%ESame as %e, format floating point number using scientific notation
%gShorthand for %f and %e
%GShorthand for %F and %E
%pFormat variable address in hexadecimal

Formatting operator auxiliary directives:

SymbolFunction
*Define width or decimal precision
-Use for left alignment
+Display plus sign (+) before positive numbers
Display space before positive numbers
#Display zero ('0') before octal numbers, and '0x' or '0X' before hexadecimal numbers (depending on whether 'x' or 'X' is used)
0Pad displayed numbers with '0' instead of default space
%'%%' outputs a single '%'
(var)Mapping variable (dictionary argument)
m.n.m is the minimum total width displayed, n is the number of digits after the decimal point (if available)

Starting from Python2.6, a new string formatting function [str.format()](#) was added, which enhances string formatting capabilities.


Python Triple Quotes

In Python, triple quotes can assign complex strings.

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

The syntax for triple quotes is a pair of consecutive single or double quotes (usually used in pairs).

>>> hi = '''hi there'''
>>> hi   # repr()
'hinthere'
>>> print hi   # str()
hi
there

Triple quotes free programmers from the quagmire of quotes and special strings, maintaining a small piece of string format in the so-called WYSIWYG (What You See Is What You Get) format from start to finish.

A typical use case is when you need a piece of HTML or SQL, using triple quotes will be very handy, while using the traditional escape character system would be very tedious.

errHTML = '''

Friends CGI Demo

ERROR

%s

''' cursor.execute(''' CREATE TABLE users ( login VARCHAR(8), uid INTEGER, prid INTEGER) ''')


Unicode String

Defining a Unicode string in Python is as simple as defining a normal string:

>>> u'Hello World !'
u'Hello World !'

The lowercase "u" before the quotes indicates that a Unicode string is being created here. If you want to include a special character, you can use Python's Unicode-Escape encoding. As shown in the following example:

>>> u'Hellou0020World !'
u'Hello World !'

The replaced u0020 identifier indicates inserting a Unicode character (space character) with the code value 0x0020 at the given position.


Python String Built-in Functions

String methods were gradually added from Python1.6 to 2.0 -- they were also added to Jython.

These methods implement most of the methods of the string module, as shown in the table below, which lists the currently supported built-in string methods. All methods include support for Unicode, some are specifically for Unicode.

MethodDescription
[string.capitalize()](#)Capitalizes the first character of the string
[string.center(width)](#)Returns a centered string padded with spaces to a total length of width
[string.count(str, beg=0, end=len(string))](#)Returns the number of times str occurs in string. If beg or end are specified, returns the number of times str occurs within the specified range.
[string.decode(encoding='UTF-8', errors='strict')](#)Decodes string using the encoding specified by encoding. If an error occurs, a ValueError exception is raised by default, unless errors is set to 'ignore' or 'replace'.
[string.encode(encoding='UTF-8', errors='strict')](#)Encodes string using the encoding specified by encoding. If an error occurs, a ValueError exception is raised by default, unless errors is set to 'ignore' or 'replace'.
[string.endswith(obj, beg=0, end=len(string))](#)Checks if the string ends with obj. If beg or end are specified, checks if the specified range ends with obj. Returns True if yes, otherwise returns False.
[string.expandtabs(tabsize=8)](#)Converts tab characters in string to spaces. The default number of spaces per tab is 8.
[string.find(str, beg=0, end=len(string))](#)Detects if str is contained in string. If beg and end specify a range, checks if contained within the specified range. If yes, returns the starting index value, otherwise returns -1.
[string.format()](#)Formats the string
[string.index(str, beg=0, end=len(string))](#)Same as find() method, but raises an exception if str is not in string.
[string.isalnum()](#)Returns True if string has at least one character and all characters are alphanumeric, otherwise returns False.
[string.isalpha()](#)Returns True if string has at least one character and all characters are letters, otherwise returns False.
[string.isdecimal()](#)Returns True if string contains only decimal digits.
← Python ListsFunc Number Radians β†’