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.
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]‘ ‘
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 |
txt
= "I love apples, apple are my favorite fruit" x
= txt.count("apple") print(x)
Output:
2 |
|
1. Write a program to count the number of times a character occurs in the given 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 |
|
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.😁
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHELPFUL
ReplyDelete