Example HTML page

Strings in Python

Strings

 A set of sequence of characters are called as “Strings”. Strings are represented in quotes(‘ ‘).

Creating strings

The strings can be created in the following ways.

>>> s=’Python’

>>> s=”Python”

>>> s=”’Python”’

>>> s=”’Hi!                                           #To extend multiple lines we can declare string within triple quotes

Welcome

To

VMS”’

Strings slicing

In general, slicing refers to partitioning. If you want to refer the sub parts of a string we perform slicing operation on strings. The slice s[start:end] is the items beginning at start and extending up to but not including end. Subsets of strings can be taken by using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and in the case of referring the string in reverse order the index position is -1.

Ex: Let the string be d=”Orange”.

O r a n g e
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

The above figure represents the word “Orange” with indexes. It starts with index position 0 and in the case of reverse string the index position starts from -1.

>>> d=”Orange”

>>> d

‘Orange’

>>> d[-1]

‘e’

>>> d[-4]

‘a’

>>> d[:-3]

‘Ora’

>>> d[-3:]

‘nge’

>>> d[2]

‘a’

>>> d[0]

‘O’

Some of the basic operations on strings are shown in below

>>> a=”python”

>>> a

‘python’

>>> st1=”fruits”

>>> st1

‘fruits’

>>> st2=”vegetables”

>>> st2

‘vegetables’

>>> st1=2*st2                                                                   #String repetition

>>> st1

‘vegetablesvegetables’

>>> string=”hello python”

>>> string

‘hello python’

>>> print(string[0])

h

>>> print(string[1:10])

ello pyth

>>> print(string[2:5])

llo

>>> print(string[2:])

llo python

>>> print(string[:2])

he

>>> print(string*2)

hello pythonhello python

>>> print(string+”programming”)                                 #String concatenation

hello pythonprogramming

Updating Strings

 You can update an existing string by reassigning another value to that string.

Ex

>>> str=”Welcome to all”

>>> str

‘hello to all’

>>> print(“Updated string is:”,str[:0]+”hello”,str)

Updated string is:  hello Welcome to all

String methods

Some of the string methods are illustrated in below:

1.capitalize( ): capitalizes first letter of a string.

Ex:

>>> str=”programming world”

>>> str.capitalize( )

‘Programming world’

2. isalnum( ): it checks whether the string consists of alphanumeric characters or not.

Ex:

>>> a=”welcometo2018″

>>> print(a.isalnum( ))

True

>>> b=”this is a string method”

>>> print(b.isalnum( ))

False

3. islower( ): Checks whether all the characters (letters) of the string are lowercase or not.

Ex:

>>> str=”INDIA is Our NatIOnal country”

>>> str.islower( )

False

>>> str1=”india is our national country”

>>> str1.islower( )

True

4.isspace( ):  Checks whether the string consists of white space/blank space.

Ex:

>>> s=””

>>> s.isspace( )

False

>>> s=” ”

>>> s.isspace( )

True

>>> s=”howareyou”

>>> s.isspace( )

False

5. istitle( ): all the first letters turns into uppercase.

Ex:

>>> a=”welcome to python”

>>> a.istitle( )

False

>>> b=”Welcome To Python”

>>> a.istitle( )

False

6. isupper( ): Checks whether all characters (letters) of the string are uppercase or not.

Ex:

>>> a=”THIS IS STRING METHOD EXAMPLE”

>>> a.isupper( )

True

>>> b=”this is string method example”

>>> b.isupper( )

False

7.len( ): Returns the length of the string.

Ex:

>>> T=”this is python programming”

>>> len(T)

26

>>> T=””

>>> len(T)

0

>>> T=” ”

>>> len(T)

1

8. lower( ) and upper( ): Returns a copy of the string in which all characters have been lower cased and upper cased.

Ex:

>>> string=”hello”

>>> string.lower( )

‘hello’

>>> string.upper( )

‘HELLO’

9. lstrip( ): Returns a copy of the string in which all chars have been stripped from the beginning(from left) of the string(default white space characters).

Ex:

>>> text=”*****wikipedia*****”

>>> text

‘*****wikipedia*****’

>>> text.lstrip(‘*’)

‘wikipedia*****’

>>> text.lstrip(‘*wi’)

‘kipedia*****’

>>> text.lstrip(‘*wiki’)

‘pedia*****’

10.rstrip( ): Returns a copy of the string in which all chars have been stripped from the end(from right) of the string (default white space characters).

Ex:

>>> text=”*****wikipedia*****”

>>> text

‘*****wikipedia*****’

>>> text.rstrip(‘*’)

‘*****wikipedia’

>>> text.rstrip(‘dia*’)

‘*****wiki

pe’

11.min( ) and max( ): Returns the min and max alphabetical character from the string.

Ex:

>>> s=”hello all…here i am”

>>> max(s)

‘r’

>>> min(s)

‘ ‘

Strings immutability

Python strings are “immutable” which means they cannot be changed after they are created. We cannot change strings once they created but we can add new value to the existing string. Suppose a string is “me” we can add another string called “here” to it by using ‘plus’ operator then (“me”+”here”) the resultant new string is “mehere”.

Example programs

1.A python program to find whether the given string is a palindrome or not.

def palin(str):
    a=str(input("give a string:"))
    if len(a)<0:
        return false
    else:
        if a[1]==a[-1]:
             print("it is a palindrome")
        else:
             print("it is not a palindrome")
palin(str)

Output

give a string: lemon

it is not a palindrome

 

give a string: liril

it is a palindrome

2.A python program on string repetition.

def print_n(s,n):
    if n<=0:
        return
    else:
        print(s)
        print_n(s,n-1)
string_name=input("enter a string:")
number=int(input("enter how many times that string should print"))
print_n(string_name,number)

Output

enter how many times that string should print 3

India

India

India

3.A python program to count the number of upper case and lower case letters in a string.

def string_test(s):
    d={"UPPER_CASE":0, "LOWER_CASE":0}
    for c in s:
        if c.isupper( ):
           d["UPPER_CASE"]+=1
        elif c.islower( ):
           d["LOWER_CASE"]+=1
        else:
           pass
    print ("Original String : ", s)
    print ("No. of Upper case characters : ", d["UPPER_CASE"])
    print ("No. of Lower case Characters : ", d["LOWER_CASE"])
string_test('ThIs Is an exaMpLE Python PrOgRAm')

Output

Original String :  ThIs Is an exaMpLE Python PrOgRAm

No. of Upper case characters :  11

No. of Lower case Characters :  17

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest