Basics of Python – String

In this Page, We are Providing Basics of Python – String. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String

String

Python can manipulate string, which can be expressed in several ways. String literals can be enclosed in matching single quotes (‘) or double quotes (“); e.g. ‘hello’, “hello” etc. They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple- quoted strings), e.g. ‘ hello ‘, “hello”. A string is enclosed in double-quotes if the string contains a single quote (and no double quotes), else it is enclosed in single quotes.

>>> "doesnt"
'doesnt'
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
' "Yes., " he said. '

The above statements can also be written in some other interesting way using escape sequences.

>>> "doesn\' t" ;
"doesn ' t”
‘>>> '\"Yes,\" he said.' 
' "Yes," he said.'

Escape sequences are character combinations that comprise a backslash (\) followed by some character, that has special meaning, such as newline, backslash itself, or the quote character. They are called escape sequences because the backslash causes an escape from the normal way characters are interpreted by the compiler/interpreter. The print statement produces a more readable output for such input strings. Table 2-12 mentions some of the escape sequences.

Escape sequence

Meaning

\n

Newline.
\t

Horizontal tab.

\v

Vertical tab.

 

Escape sequence

Meaning
W

A backslash (\).

Y

Single quote (‘).
\”

Double quote (“).

String literals may optionally be prefixed with a letter r or R, such string is called raw string, and there is no escaping of character by a backslash.

>>> str=' This is \n a string '
>>> print str 
This is 
a string
>>> str=r' This is \n a string '
>>> print str 
This is \n a string

Specifically, a raw string cannot end in a single backslash.

>>> str=r ' \ '
File "<stdin>", line 1 
str=r ' \ '
            ∧
SyntaxError: EOL while scanning string literal

Triple quotes are used to specify multi-line strings. One can use single quotes and double quotes freely within the triple quotes.

>>> line=" " "This is
. . . a triple
. . . quotes example" " "
>>> line
' This, is\na triple\nquotes example'
>>> print line
This is
a triple 
quotes example

Unicode strings are not discussed in this book, but just for the information that a prefix of ‘ u ‘ or ‘ U’ makes the string a Unicode string.

The string module contains a number of useful constants and functions for string-based operations. Also, for string functions based on regular expressions, refer to re module. Both string and re modules are discussed later in this chapter.

Python String Programs