Strings in Python

Strings in python

STRINGS

As mentioned earlier, a string is a sequence of characters, A string may be specified by placing the member characters of the sequence within quotes single, double or triple). Triple quotes are typically used for strings that span maltiple lines. The following assignment statement assigns the string Hello Gita' to the variable message. We may also say that the aming "Hello Gita' has been bound to the name message.
>>> message 'Hello Gita'
Python function Len finds the length of a string. Thus,
>>> len (mensage)
10

Individual characters within a string are accessed using a technique known as indexing. we illustrate the notion of indexing with the help of the string 'Hello Gita'.
Note that the indices start with 0 (index for accessing the first character from the left) and end with one less than the length of the string (index for accessing the last character). The following instructions illustrate how access individual characters in a string via indices. An index is specified within the sqaure brackets, for example:
>>> message [0]
>>> message [6]
'G'
>>> index = len (message) -1
>>> message [index]
'a'

The expression message [0] yields character 'H' since 'H' is stored at index 0. Similarly, the value of len (message) being 10, when index is set equal to len (message) -1, message [index] yields the last character of the string message at index 9, i.e. 'a'. Sometimes it is more convenient to access the elements of a string from the right end. For this purpose, Python provides negative indices. The negative indices range from -(length of the string) to -1. For the string message, the negative indices would range from -10 to -1. Thus, the entire range of valid indices would ng from the right be 1-10, -9, -1, 0, 1, 9). Consequently, message [-1] would yield 'a' and message [-index] would yield 'e':
>>> message [-1]
>>> message [-index]

If we try to access an index which is not in the valid index range of a string, IndexError will be generated:
Strings in Python are immutable, i.e., a component of a string cannot be altered, and an attempt to do so would lead to an error:
As mentioned earlier, strings can be concatenated using concatenation operator and can be repeated a multiple number of times using the operator *.
>>> 'Computer' + ' Science'
'Computer Science'
>>> 'Hi' * 3
'HiHiHi'

Strings may also be compared using relational operators mentioned in chapter 1. Also, recall that the functions max and min may be used to find maximum and minimum respectively of several values, for example:
>>> max ('AZ', 'C', 'BD', 'BT')
>>> min ('BD', 'AZ', 'C') 'AZ'
>>> max ('hello', 'How', 'Are', 'You', 'str')
'sir'

introduction python Function in python

0 Response to "Strings in Python"

ads