Previous | Next

String is used to represent text which comprised of a set of characters that can be spaces, numbers, etc. Python’s strings support the sequence type method which means you can deal with the string by using sequence type method like splitting, slicing, indexing, membership, length, etc. Strings are immutable, so all kinds of item or slice assignments are illegal.

Creating of strings:

Creating of strings is simple, use either single or double quotes within a string. BTW, there is no different between single or double quotes in Python string.
>>> str1 = 'Hello'
>>> str2 = "String"

String formatting:

String formatting uses the string formatting operator, the percent (%) sign. To the left of the %, you place a string (the format string); to the right of it, you place the value you want to format.
>>> print '%s %s' % (str1, str2)
Hello String
If you are formatting integer numbers, you can use the d specifier type.
>>> age = 25
>>> print 'I am %d years old' % (age)
I am 25 years old
If you are formatting real numbers (floats), you can use the f specifier type and supply the precision as a . (dot), followed by the number of decimals you want to keep.
>>> value = 1.288
>>> print 'value is %.5f' % (value)
value is 1.28800
Here is the list of complete set of symbols which can be used along with %:
Convertion Type Description
%c Single character (accepts an integer or a single character string)
%s String (converts any Python object using str)
%r String (converts any Python object using repr)
%d, %i Signed integer decimal
%o Unsigned octal
%u Unsigned decimal
%x Unsigned hexadecimal (lowercase)
%X Unsigned hexadecimal (uppercase)
%e Floating-point exponential format (lowercase)
%E Floating-point exponential format (uppercase)
%f, %F Floating-point decimal format
%g Same as e if exponent is greater than –4 or less than precision; f otherwise
%G Same as E if exponent is greater than –4 or less than precision; F otherwise


The width is the minimum number of characters reserved for a formatted value. In the following example, we reserved 10 characters space for str1 string.
>>> print '%10s' % (str1)
You can use an * (asterisk) as the width. In that case, the number will be read from the tuple argument:
>>> print '%*s' % (10, str1)


Sometimes, you may want to pad additional zero in the formatted string. In the following example, we reserved 10 characters space for the string output. The leading zero will convert the empty spaces to zero (0).
>>> number = 1980
>>> print '%010d' % (str1)
>>> number = 1980
>>> print '%0*d' % (10, str1)

Escape Characters:

Like C or C++ programming, Python support escape characters that can be presented with backslash notation. Escape sequences are used to insert characters in a string that would otherwise be impossible to specify, such as tab and newline, or in some circumstances would confuse the compiler, such as placing a double quote, which you would normally use to delimit a string, within a string. The character following the backslash indicates what character the escape sequence represents. The following example will include a single quote into a string.
>>> print 'I\'m John'
I'm John
The following example will print 2 lines of string by using newline escape ‘\n’
>>> print 'This is line1\nThis is line2'
This is line1
This is line2
The following example will use a tab escape ‘\t’
>>> print 'Hello\tJohn'
Hello John
Here is the list of escape characters that can be represented with backslash notation:
Backslash notation Description
\n Newline
\’ Single quote
\” Double quote
\b Backspace
\a Alert or bell
\e Escape
\f Formfeed
\r Carriage return
\s Space
\t Tab

Long strings:

If you want to write a really long string, one that spans several lines, you can use triple quotes instead of ordinary quotes:
>>> print '''This is line 1
this is line 2
this is line 3'''

This is line 1
this is line 2
this is line 3

Concatenating Strings:

Use the + operator to concatenate strings into a single string.In the following example, str3 is the concatenation output of str1, a space, and str2
>>> str1 = 'Hello'
>>> str3 = 'World'
>>> str3 = str1 + ' ' + str2
>>> print str3
Hello World

Raw strings:

Raw strings don’t treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it. Raw strings use the prefix r.
>>> print r'C:\directory'
>>> print r'Let\'s jump!'
Let\'s jump!

Unicode strings:

Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. Unicode strings use the prefix u.
>>> print u'Hello world!'
Hello world!

Useful String methods:

Python strings have a much richer set of methods. Because there are so many string methods, only some of the most useful ones are described here.
Method Description
find() Finds a substring within a larger string. It returns the leftmost index where the substring is found. If it is not found, –1 is returned.
>>> movie = "The adventure of tintin"
>>> movie.find('tintin')
split() To split a string into a sequence.
>>> movie = "The adventure of tintin"
>>> movie.split()
['The', 'adventure', 'of', 'tintin']
join() It is the inverse of split(). It is used to join the elements of a sequence.
>>> names = 'alex', 'james', 'kelvin'
>>> '->'.join(names)
lower() Returns a lowercase version of the string.
>>> str = 'ADVENTURE'
>>> str.lower()
upper() Returns a uppercase version of the string.
>>> str = 'adventure'
>>> str.upper()
replace() Replace all the occurrences of string by another. In the following example, message will be replaced by messageeeeezzz.
>>> str = 'Sample message to send'
>>> str.replace('message', 'messageeeeezzz')
'Sample messageeeeezzz to send'
strip() Stripped (removed) the whitespace on the left and right of a string.
>>> str = '   String with whitespace    '
>>> str.strip()
'String with whitespace'

Previous | Next