Strings

Introduction

The purpose of Revision Tour Chapters is to brush up all concepts. This chapter is going to help you recall and brush up concepts of strings.

Strings in Python

Strings in python are stored as individual characters in contiguous locations, with two-way index for each location i.e. Forward Indexing and Backward Indexing.
The characters of the strings are given two-way indices:

  • 0,1,2... size-1 in the forward direction and
  • -1, -2, -3 .... -size in the backward direction
Thus we can access any character as <stringname>[<index>]e.g., to access the first character of sting name, we'll write name[0], because the index of first character is 0. You may also write name[-6] for example i.e., when string name is storing "PYTHON".
Length of string variable can be determined using function len(<string>), i.e. to determine length of above shown string name.

Item Assignment not supported


One important thing about python strings is that you cannot change the individual letters of a string by assignment because strings are immuntable and hence item assignment is not supported.

Traversing a string


Traversing refers to iterating through the elements of a string, one character at a time.To traverse through a string, we can write a loop like:

            
                code = "Powerful"
                for ch in code:
                    print(ch,'~', end='')
            
        
Output:
            
                P~o~w~e~r~f~u~l~
            
        

String Operations


  • String Concatenation Operator +
    The + operator creates a new string by joining the two operand strings.
    "Power"+"ful"
    will result into
    'Powerful'
    The + operator has to have both operands of the same type either of number types or of string types. It cannot work with one operand as string and one as a number.
  • String Replication Operator *
    To use a * operator with strings, you need two operands - a string and a number i.e. as number * string or string * number, where string operand tells the string to be replicated and number operand tells the number of times, it is to be repeated; Python will create a new string that is a number of repetitions of the string opreand.
  • Membership Operators
    There are two membership operators for strings(infact, for all sequence types). These are in and not in.
    
                        in  returns True if a character or a substring exists otherwise false
                        not in  returns True if a character or a substrings does not exists otherwise false.
                    
    For example:
                        
                            >>>"a" in "heya"
                            True
                            >>>"jap" in "heya"
                            false
                            >>>"jap" in "Japan"
                            false
                            >>>"help" not in "hellothere"
                            True
                        
                    
  • Comparison Operators
    Python's standard comparison operators i.e. all relational operators(<,<=,>,>=,==,!=), apply to strings also. The comparisons using these operators are based on the standard character-by-character comparison rules for ASCII or Unicode (i.e. dictionary order).String are compared on the basis of lexicographical ordering, upper-case letters are considered smaller than lower-case letters.
    In order to determine the ASCII value or Unicode value, python offers a built-in function ord() that takes a single character and returns the corresponding ASCII or Unicode value.
    ord(<single-character>)

String Slices


The term 'string slices' refers to a part of the string, where strings are sliced using range of indices. That is, for a string say name, if we give name[n:m] where n and m are integers and legal indices, python will return a slice of the string by returning the characters falling between indices n and m: strating at n, n+1, n+2, ... till m-1.
For example: consider a string word storing "amazing"

                    
                        >>>word[3:], word[:3]
                        'zing''ama'
                        >>>"word[:3]+word[3:]
                        'amazing'
                        >>>word[::-1]
                        gnizama
                    
                

String Functions


Python also offers many builtin functions and methods for string manipulation, The string manipulation methods that are being discussed below can be applied to strings as per following sytax:
<stringObject>.<methodname>()
For instance, if you have a string namely str="Rock the World." and you want to find its length you will srite the code shown below:
                    
                        >>>str = "Rock the World."
                        >>>str.length()
                        15
                    
                
Function Name Purpose
string.capitalize() Returns a copy of the string with it s first character capitalized.
string.find(sub[,start[,end]]) Returns the lowest index in the string where the substring sub is found within the slice range of start and end. Returns -1 if sub is not found.
string.isalnum() Returns true if the characters in the string are alphanumeri and there is atleast one characte,False otherwise
string.isalpha() Returns true if all characters in the string are alphabetic and there is ateast one character otherwise false.
string.isdigit() Returns true if all the characters in the string are digits. There must be one digit, false otherwise
string.isspace() Returns true if there are only whitespace characters in the string. There must be atleast one character. It returns false otherwise.
string.islower() Returns true if all cased characters in the string are lowercase. There must be atleast one cased character. It returns false otherwize
string.isupper() Tests whether all cased characters in the string are uppercase() and requires that there be atleast one cased character.
string.lower() Returns a copy of the string converted to lowercase
string.upper() returns a copy of the string converted to uppercase