Saturday, November 21, 2020

String

 

STRING IN PYTHON

 

Definition: String is a collection of characters. Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings. Python does not have a character data type, a single character is simply a string with a length of 1.

 

    Basics of String:

  •    Strings are immutable means that the contents of the string cannot be changed after it is created. At the same memory  address, the new value cannot be stored. Python does not allow the programmer to change a character in a string. 

 Example:

>>>str='jaipur'

>>>strTypeError: 'str' object does not support item assignment .

As shown in the above example.As shown in the above example, str has the value “jaipur”. An attempt to replace ‘j’ in the string by ‟J‟ displays a TypeError.

  • Each character has its index or can be accessed using its index.
  • String in python has two-way index for each location. (0, 1, 2, ……. In the forward direction and -1, -2, -3,......... in the backward direction.)




Important points about accessing elements in the strings using subscripts

  • Positive subscript helps in accessing the string from the beginning
  • Negative subscript helps in accessing the string from the end.
  • Subscript 0 or –ve n(where n is length of the string) displays the first element.
  • Example : A[0] or A[-5] will display "H"
  • Subscript 1 or –ve (n-1) displays the second element.
Basic String Operators 

a) String Concatenation Operator (+)
      the + operator creates a new string by joining the operand strings.
    e.g.
      "Hello" + "Students"
      will result into :  "HelloStudents"
       '11' + ‘22’      will give: ‘1122'
       "a" + "5"      will give : "a5" 
       '123' + 'abc'  will give: '123abc‘
 
       "a"  + 5       is invalid     
Note: both operands must be strings.


b) String Replication Operator (*)
   The '*' operator when used with String, then it creates a new string that  is a number of  replications of the input string.
    e.g.  
    "XY" * 3   will give: "XYXYXY"
     "3" * 4    will give: "3333“
      "5" * "7"  is invalid
Note: operands must be one string & other Number

Membership Operators: (in & not in)

in returns True if a character or a  substring exists in the given string,  False   otherwise.
       
"a" in "Rajat"    gives: True
"Raj" in "Rajat" gives: True
 "67"  in "1234" gives: False

not in: returns True if a character or a substring does not exists in   the given string, 
False otherwise.
 "a" not in "Rajat"    gives: False
"Raj“ not in "Rajat" gives: False
 "67" not in "1234"  gives: True

ord() & chr() functions
ord() function:
   It gives ASCII value of a single character
   ord ("a")   : 97
   ord ("Z")   : 90
   ord("0")   : 48
chr() function:
   it is opposite of ord() function
     chr(97)   : “a" 
     chr(90)   : “Z"
     chr(48)  : “0”

String Slice :


Extracting a subpart from a main string is called slicing .It is done by using a range of indices.
Syntax:

>>>string-name[start:stop:step]

Note: it will return a string from the index start to stop-1.
Example:
>>> s="TEACHER"

0

1

2

3

4

5

6

T

E

A

C

H

E

R

-7

-6

-5

-4

-3

-2

-1

>>> s[2:6:1]    'ACHE'

>>> s[6:1:-1]    'REHCA'

>>> s[0:10:2] 'TAHR'

>>> s[-8:-3:1] 'TEAC

>>> s[ : 6 : 1] # Missing index at start is considered as 0. 'TEACHE'

>>> s[2 : :2] # Missing index at stop is considered as last index. 'AHR'

>>> s[3:6: ] # Missing index at step is considered as 1. 'CHE'

>>> s[ : :-1] 'REHCAET'

>>> s[2: :]+s[ :2 :] 'ACHERTE'

>>> s[1: 5:-1]

 
 Let word=“WelCome
Then,
        word [0:7]     will give   : WelCome
        word [0:3]     will give   : Wel
        word [2:5]     will give   : lCo       (2,3,4)
        word [-6:-3]   will give   : elC      (-6,-5,-4)
        word [  :5]      will give   : WelCo      (0,1,2,3,4)
        word [3:  ]      will give   : Come       (5,6,7,8)


for loop with string
e.g.1:
for  ch  in  “Hello” :
  print(ch)
Output:
  H
  e
  l
  l
  o 


Built-in functions of string:

 

str=”data structure”

s1= “hello365”

s2= “python”

s3 = ‘4567’

s4 = ‘ ‘

s5= ‘comp34%@’

 

 

 

S.

No.

Function

Description

Example

1

len( )

Returns the length of a string

>>>print(len(str)) 14

2

capitalize( )

Returns the copy of the string with its first character capitalized and the rest

of the letters are in lowercased.

>>> s1.capitalize() 'Hello365'

3

find(sub,start,en d)

Returns the index of the first occurence of a substring in the given string (case-sensitive). If the substring is not found it returns -1.

>>>s2.find("thon",1,7) 3

>>> str.find("ruct",8,13)

-1

4

isalnum( )

Returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False.

>>>s1.isalnum( ) True

>>>s2.isalnum( ) True

>>>s3.isalnum( ) True

>>>s4.isalnum( ) False

>>>s5.isalnum( ) False

5

isalpha( )

Returns True if all characters in the string arealphabetic. False otherwise.

>>>s1.isalpha( ) False

>>>s2.isalpha( ) True

>>>s3.isalpha( ) False

>>>s4.isalpha( ) False

>>>s5.isalpha( )

False

6

isdigit( )

Returns True if all the characters in the string aredigits. False otherwise.

>>>s1.isdigit( ) False

>>>s2.isdigit( ) False

>>>s3.isdigit( ) True

>>>s4.isdigit( ) False

>>>s5.isdigit( ) False

7

islower( )

Returns True if all the characters in the string arelowercase. False otherwise.

>>> s1.islower() True

>>> s2.islower() True

>>> s3.islower() False

>>> s4.islower() False

>>> s5.islower()

True

8

isupper( )

Returns True if all the characters in the string areuppercase. False otherwise.

>>> s1.isupper() False

>>> s2.isupper() False

>>> s3.isupper() False

>>> s4.isupper() False

>>> s5.isupper() False

9

isspace( )

Returns True   if    there are only

>>> " ".isspace() True

>>> "".isspace() False

10

lower( )

Converts a string in lowercase characters.

>>> "HeLlo".lower() 'hello'

11

upper( )

Converts a string in uppercase

characters.

>>> "hello".upper() 'HELLO'

12

lstrip( )

Returns a string after removing the leading characters. (Left side). if used without any argument, it removes theleading whitespaces.

>>> str="data structure"

>>> str.lstrip('dat') ' structure'

>>> str.lstrip('data')' structure'

>>> str.lstrip('at') 'data structure'

>>> str.lstrip('adt') ' structure'

>>> str.lstrip('tad') ' structure'

13

rstrip( )

Returns a string after removing the trailingcharacters. (Right side).

if used without any argument, it removes thetrailing whitespaces.

>>> str.rstrip('eur') 'data struct'

>>> str.rstrip('rut') 'data structure'

>>> str.rstrip('tucers')'data '

14

split( )

Splits the string from the specified separator and returns a list object with string elements.

>>> str="Data Structure"

>>> str.split( ) ['Data', 'Structure']

15

Count()

The count() method returns the number of times a specified value appears in the string.

txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)

 

Output: 2

 

Practical Programs using string functions and operators


1. Write a program to count the number of times a character occurs in the given string.


string = input("Enter a string :-")
for i in string :
      print(i, "=", string.count(i), "times")


2. Write a program which reverses a string and stores the reversed string in a new string.

string = input("Enter a string :-")
newstring = string[-1:-len(string)-1:-1]
print(newstring)


3. Write a program that:

Prompt the user for a string.
Extract all the digit from the string.
If there are digits:
Sum the collected digits together.
Print out:
  (1). The original string
  (2). The digits
  (3). The sum of the digits
 If there are no digits: Print the original string and massage "has no  digit".

a = input("Enter a string = ")
sum = 0
digit = ""

for i in a :
    if i.isdigit() :
        sum += int(i)
        digit += i
        
if sum == 0 and len(digit) == 0:
    print(a, "has no digit")
else :
    print("Original string = ", a)
    print("Digits are ", digit)
    print("Sum of all digit = ", sum)


Q.4 Write a program that inputs a line of text and prints out the count of vowels in it.
string = input("Enter a string :-")
count = 0
for i in string :
    if i == "a" or i == "e" or i == "i" or i == "o" or i == "u" or i == "A" or i == "E" or i == "I" or i == "O" or i == "U":
        count += 1
print("Number of vowel :-", count)


Q. 5 Write a program to Check if a String is a Palindrome 

def isPalindrome(string): 
    if (string == string[::-1]) : 
        return "The string is a palindrome." 
    else: 
        return "The string is not a palindrome." 
 
#Enter input string 
string = input ("Enter string: ") 
 
print(isPalindrome(string)) 


Exercise Questions:     String


 

 

1 Mark Questions

 

 

Q.No

Question

Answer

 

1.

print the string “India” 10 times.

>>>”india”*10

 

2.

What is the output of the following code

>>>‘a’ in “computer”

False

 

3.

What is the output of the following code

Strg=”computer”

print(Strg[ 0: 8 : 2]

‘cmue’

 

4.

What is the output of the following?

print('INDIA'.capitalize())

“India”

 

5.

(i) “Hello”     (ii) ‘Hello’

(iii) “Hello’    (iv) None of the above

(iii) “Hello’

 

6.

Suppose word = ‘amazing’, the what will

be word[: : -2]?

‘giaa’

 

2 Mark Questions

 

 

Sr.

Question

Answer

 

1.

If you give the following for str1=”Hello” why does python report error str1[2]=’p’

String is immutable data type.So it does not support item assignment

 

2.

Identify the output of the following Python statements.

x="Vidyalaya" y="Vidya"

if(y in x):

print(y)

Vidya

 

3.

Look at the code sequence and select the correct output

str="KVS RO Jaipur" for i in str: if(i.isupper()==True):

print(i.lower(),end="") if(i.islower()==True):

print(i.upper(), end="")

kvsrojAIPUR

 

4.

Find the correct output of the following

>>>str="The planet earth looks like a blue marble from outer space"

>>>print(str.find('marble',50))

-1

 

5.

Find the value stored in ctr at the end of this code snippet:

mystr="Darjeeling Tea has a strong flavour"

ctr=0

for i in mystr:

if i in 'aeiouAEIOU': ctr += 1

print(ctr)

12

 

 

3 Mark Questions

 

 

Sr.

Question

Answer

 

1.

Write a Python program to input a line of text and a character from user to print the frequency of the character in the line. For example

Line entered is : this is a golden pen The character to search : e

Then output is : Frequency is 2

line=input ("Enter a line of text :") ch=input ("Enter a character to search ")

k=line.count(ch)

print ("Frequency is :",k)

 

2.

Write a Python Program to input a string to check whether it is a Palindrome string or not. (A Palindrome string is that which is same from both ends like – NITIN, MALAYALAM, PULLUP)

s=input("Enter a word :") print ("You entered :", s) length=len(s)

rev=""

for i in range (-1,-length-1,-1): rev=rev+s[i]

if s==rev:

print ("Yes, palindrome")

else:

print ("Not a palindrome")

 

3.

Using string replication techniques print the following pattern using any loop.


Hello 

Hello Hello

Hello Hello Hello

for a in range(1,4): print("hello " * a)

 

 

4 Mark Questions

 

 

Sr.

Question

Answer

 

1.

Find Output:

my_string = 'Jhunjhunu' print(my_string[:3])

for i in range(len(my_string)): print(my_string[i].upper(),end="@")

print()

print (my_string) print (my_string[3:6])

 

Jhu J@H@U@N@J@H@U@N@U@ Jhunjhunu

njh

 

2.

Consider the following string mySubject: mySubject = "Computer Science"

What will be the output of the following string operations : print(mySubject[0:len(mySubject)]) print(mySubject[-7:-1]) print(mySubject[::2]) print(mySubject[len(mySubject)-1]) print(2*mySubject)

print(mySubject[::-2])

Computer Science Scienc

Cmue cec e

Computer ScienceComputer Science eniSrtpo

 

3.

Consider the following string country: country= "Great India"

What will be the output of the following string operations(Any Four):-

a)  print(country[0:len(country)])

b)  print(country[-7:-1])

c)  print(country[::2])

d)  print(country[len(country)-1])

e)  print(2*country)

f)  print(country[:3] + country[3:])

a) Great India

b) t Indi c)GetIda d)a

e) Great IndiaGreat India

f) Great India

 


3 comments:

  1. Samajh me to aa rha hay. Jis video se me kar rha hu usme bhi poora ka poora apka he blog copy kr rakha h.😁

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete