Basics of Python – String Operations

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

Basics of Python – String Operations

String operations

Some of the string operations supported by Python are discussed below.

Concatenation

Strings can be concatenated using + operator.

>>> word=' Python '+' Program '
>>> word
' Python Program '

Two string literals next to each other are automatically concatenated; this only works with two literals, not with arbitrary string expressions.

>>> ' Python ' ' Program '
' Python Program ' 
>>> word1=' Python '
>>> word2=' Program '
>>> word1 word2
File "<stdin>", line 1
word1 word2
                   ∧
SyntaxError: invalid syntax

Repetition

Strings can be repeated with the * operator.

>>> word=' Help '
>>> word * 3
' Help Help Help '
>>> 3 * word
' Help Help Help '

Membership operation

As discussed previously, membership operators in and not in are used to test for membership in a sequence.

>>> word=' Python '
>>> 'th' in word
True
>>> ' T ' not in word
True

Slicing operation

The string can be indexed, the first character of a string has sub-script (index) as 0. There is no separate character type; a character is simply a string of size one. A sub-string can be specified with the slice notation.

>>> word=' Python'
>>> word [2]
' t '
>>> word [0:2]
' Py '

String slicing can be in form of steps, the operation s [ i : j : k ] slices the string s from i to j with step k.

>>> word [1 :6 : 2]
' yhn '

Slice indices have useful defaults, an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word [ : 2]
' Py '
>>> word [2 : ]
' thon '

As mentioned earlier, the string is immutable, however, creating a new string with the combined content is easy and efficient.

>>> word [0] = ' J '
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
TypeError : 'str' object does not support item assignment
>>> 'J ' + word[ 1 : ]
' Jython '

If the upper bound is greater than the length of the string, then it is replaced by the string size; an upper bound smaller than the lower bound returns an empty string.

>>> word [ 2 : 50 ]
'thon '
>>> word [ 4 : 1 ]
' '

Indices can be negative numbers, which indicates counting from the right-hand side.

>>> word [ -1 ]
' n '
>>> word [ -2 ]
' o '
>>> word [ -3 : ] 
' hon '
>>> word [ : -3 ]
' Pyt ' 
>>> word[-0]     # -0 is same as 0
' P '

Out-of-range negative slice indices are truncated, but a single element (non-slice) index raises the IndexError exception.

>>> word [ -100 : ]
' Python '
>>> word [ -100 ]
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
IndexError : string index out of range

String formatting

String objects have an interesting built-in operator called modulo operator (%). This is also known as the “string formatting” or “interpolation operator”. Given format%values (where a format is a string object), the % conversion specifications in format are replaced with zero or more elements of values. The % character marks the start of the conversion specifier.

If the format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (a dictionary). If the dictionary is provided, then the mapping key is provided in parenthesis.

>>> ' %s Python is a programming language. ' % ' Python '
' Python Python is a programming language. '
>>> ' %s Python is a programming language. ' % ( ' Python ' )
' Python Python is a programming language.'
>>>
>>> ' %s has %d quote types. ' % ( ' Python ' , 2 )
' Python has 2 quote types. '
>>> ' %s has %03d quote types. ' % ( ' Python ' , 2 )
' Python has 002 quote types. '  
>>> ' %( language )s has % ( number ) 03d quote types.' % \
. . . { " language " : " Python " , " number " : 2 }
' Python has 002 quote types. '

In the above example, 03 consists of two components:

  • 0 is a conversion flag i.e. the conversion will be zero-padded for numeric values.
  • 3 is minimum field width (optional).
Conversion Meaning
D Signed integer decimal.
1 Signed integer decimal.
E Floating-point exponential format (lowercase).
E Floating-point exponential format (uppercase).
F Floating-point decimal format.
F Floating-point decimal format.
g Floating point format. Uses lowercase exponential format if the exponent is less than -4 or not less than precision, decimal format otherwise.
G Floating point format. Uses uppercase exponential format if the exponent is less than -4 or not less than precision, decimal format otherwise.
s String.

Precision (optional) is given as a dot (.) followed by the precision number. While using conversion type f, F, e, or E, the precision determines the number of digits after the decimal point, and it defaults to 6.

>>> " Today's stock price : %f " % 50
"Today's stock price: 50 000000"
>>> "Today's stock price : %F " % 50
"Today's stock price: 50 000000"
>>>
>>> "Today's stock price : %f " % 50.4625
"Today's stock price : 50 462500"
>>> "Today's stock price : %F " % 50.4625
"Today's stock price : 50 462500"
>>>
>>> "Today's stock price : %f " % 50.46251987624312359
"Today's stock price : 50. 462520"
>>> "Today's stock price : %F " % 50.46251987624312359
"Today's stock price : 50. 462520"
>>>
>>> "Today's stock price : %. 2f " % 50 . 4625
"Today's stock price : 50.46"
>>> "Today's stock price : %. 2F " % 50 . 4625
"Today's stock price : 50.46"
>>>
>>> "Today's stock price : %e " % 50 . 46251987624312359
"Today's stock price : 5 . 046252e+01 "
>>> "Today's stock price : %E " % 50 . 46251987624312359
"Today's stock price : 5 . 046252e+01 "
>>> "Today's stock price : % 3e " % 50 . 46251987624312359
"Today's stock price : 5 . 046e + 01 "
>>> "Today's stock price : % 3E " % 50 . 46251987624312359
"Today's stock price : 5 . 046E + 01 "

While using conversion type g or G, the precision determines the number of significant digits before and after the decimal point, and it defaults to 6.

>>> " Today's stock price : %g" % 50.46251987624312359
"Today's stock price: 50.4625"
>>> "Today's stock price: %G" % 50.46251987624312359
"Today's stock price: 50.4625"
>>>
>>> "Today's stock price: %g" % 0.0000005046251987624312359
"Today's stock price: 5.04625e-07"
»> "Today's stock price: %G" % 0.0000005046251987624312359
"Today's stock price: 5.04625E-07"

Python String Programs