Python_Strings

 String Data Type

===============
What is a string?
Any sequence of characters within either single or double or triple quotes is considered as a string.

Ex:
s = 'sunny'
s = "sunny"
s = '''sunny'''
s = """sunny"""

How to define multiline string:
-----------------------------------------------
s = '''Naresh
It
Technologies'''
print(s)

Ex:
-----
'This is a ' single code symbol' #invalid
"This is a ' single code symbol" #Valid
'This is a \' single code symbol' #Valid

How to access characters of a string:
-------------------------------------------------------
1).By using index:
-->Python supports both +ve and -ve index.
-->+ve index means left to right(forward direction)
-->-ve index means right to left(backward direction)
Ex:
s = 'sunny'
s[0] #s
s[-1]#y
s[10]#IndexError

Q.w.a.p to accept some string from the keyboard and display its characters by index wise(both +ve and -ve)

s = input('Enter some string:')
i = 0
for x in s:
print('The character present at +ve index:{} and -ve index:{} is:{}'.format(i,i-len(s),x))
i += 1

2).By using slice operator:
---------------------------------------
Syn:
s[Begin:End:Step]

Begin index:From where we have to consider slice(substring)
End index:We have to terminate the slice at endindex-1
Step:Increment value

Ex:
-----
s = 'learning python is very easy'
s[1:7:1] #'earnin'
s[1:7] #'earnin'
s[:7] #'learnin'
s[7:] #'g python is very easy'
s[:] #'learning python is very easy'
s[::] #'learning python is very easy'
s[::-1] #'ysae yrev si nohtyp gninrael'

Ex:
-----
s = '0123456789'
s[2:8:1]
s[2:8:-1]
s[-1:-6:-1]
s[2:-5:1]
s[-5:0:-1
s[:0:-1]

_______________________________________________________________________________________________________________________

Behaviour of slice operator:
-----------------------------------------
1).If step is positive: | 2).If step is negative:
-------------------------------_____|-------------------------------
-->forward direction(left to right) |-->backward direction(right to left)
-->Default value for begin index:0 |-->Default begin index:-1
-->begin to end-1 |-->begin to end+1

Note:
-->In the backward direction if end value is -1 then result is always empty.
-->In the forward direction if end value is 0 then result is always empty.

Ex:
-----
s = '0123456789'
s[2:8:1]#234567
s[2:8:-1]#''
s[-1:-6:-1]#'98765'
s[2:-5:1]#234
s[-5:0:-1]#'54321'
s[:0:-1]#987654321

Case Study:
------------------
>>> s="abcdefghij"
>>> s[1:6:2]#'bdf'
>>> s[::1]#'abcdefghij'
>>> s[::-1]# 'jihgfedcba'
>>> s[3:7:-1]#''
>>> s[7:4:-1]#'hgf'
>>> s[0:1000:1]#'abcdefghij'
>>> s[-4:1:-1]#'gfedc'
>>> s[-4:1:-2] #gec
>>> s[5:0:1]#''
>>> s[9:0:0]# slice step cannot be zero
>>> s[0:-10:-1]#''
>>> s[0:-11:-1]#'a'
>>> s[0:-12:-1]#'a'
>>> s[0:0:1]#''
>>> s[0:-9:-2]#''
>>> s[-5:-9:-2] #'fd'
>>> s[9:-1:-1] #''

Q6. You are developing a python application for your company.

A list named school contains 10 names,the last 3 being teachers .
You need to slice students to display all excluding teachers. Which two code segments we should use?

A) school[1:-2]
B) school[:-3]
C) school[1:-3]
D) school[0:-2]
E) school[0:-3]

Answer:B and E

Q7. You are developing a python application for your company.
A list named employees contains 500 employee names,the last 3 being company management. Which of the following represents only management employees.

A) employees[497:]
B) employees[-3:]
C) employees[497:500]
D) All the above

Answer:D

Q8. You are developing a python application for your company.
A list named employees contains 500 employee names.
In which cases we will get IndexError while accessing employee data?

A) employees[1:1000]
B) employees[-10:10]
C) employees[0:501]
D) None of the above

Answer:D

Q9. You are developing a python application for your company.
A list named employees contains 500 employee names.
In which cases we will get IndexError while accessing employee names?

A) employees[0]
B) employees[500]
C) employees[-1]
D) None of the above

Answer:B

Q10. Consider the list:

list=['Apple','Banana','Carrot','Mango']
Which of the following are valid ways of accessing 'Mango':

A) list[0]
B) list[-1]
C) list[4]
D) list[3]

Answer:B and D

Q.
str1 = 'Python Learning'
str2 = str1[:5]*2 + str1[:4]
str3 = str2[:5//2]*3
print(str3)

a).Python
b).PythonPythonPython
c).LeaLeaLea
d).PyPyPy

Answer:D

Q.3
str1 = 'Hello'
str2 = 'World'
result = str1[2:] + str2[3:]*2
print(result)

A).'HelloWorld'
B).'lloldld'
C).'WorldHello'
D).Error

Answer:B

Q38. Consider the code:
x='ACROTE'
y='APPLE'
z='TOMATO'

Which of the following won't print 'CAT' to the console

A) print(x[1]+y[0]+z[0])
B) print(x[2]+y[1]+z[1])
C) print(x[-5]+y[0]+z[0])
D) print(x[-5]+y[0]+z[-2])

Answer:B

Q. Consider the code:
s='Python is easy'
s1=s[-7:]
s2=s[-4:]
print(s1+s2)

What is the result?
A)is easyeasy
B)easyeasy
C)iseasyeasy
D)s easyeasy
E)is easy easy

Answer:A


______________________________________________________________________________________________________________________

w.a.p to access each character of string in forward direction and backward direction by using while loop?
--------------------------------------------------------------------------------------------------------------------------------
s = input('Enter some string:')#sunny
n = len(s)#5
i = 0
print('Forward direction:')
while i < n:
print(s[i],end='')
i += 1
print()


print('Backward direction:')
i = -1
while i >= -n:
print(s[i],end='')
i -= 1
print()

print('Backward direction:')
i = n-1
while i >= 0:
print(s[i],end='')
i -= 1

By using for loop:
--------------------------
s = input('Enter some string:')#sunny
print('Forward direction:')
for i in s:
print(i,end='')
print()
print('Forward direction:')
for i in s[::]:
print(i,end='')
print()
print('Backward direction:')
for i in s[::-1]:
print(i,end='')

Checking membership:
----------------------------------
s = input('Enter main string:')
subs = input('Enter sub string:')
if subs in s:
print(subs,'is found in main string')
else:
print(subs,'is not found in main string')

Comparision of string:
---------------------------------
s1 = input('Enter first string:')
s2 = input('Enter second string:')
if s1 == s2:
print('Both strings are equal')
elif s1 < s2:
print('First string is less than second string')
else:
print('First string is greater than second string')

Ex:
-----
l1 = ['A','B','C']
l2 = ['A','B','C']
l3 = l2
print(l1 is l2)#False
print(l2 is l3)#True
print(l1 == l2)#True

Removing spaces from the string:
-------------------------------------------------
1.rstrip():To remove spaces at right hand side.
2.lstrip():To remove spaces at left hand side.
3.strip():To remove spaces both sides.

city = input('Enter Your City:')
scity = city.strip()
if scity == 'hyderabad':
print('Hello Hyderabadi....good mng')
elif scity == 'chennai':
print('Hello Madrasi...Vanakkam')
elif scity == 'bangalore':
print('Hello Kannadiga...Subhodaya')
else:
print('Your entered city is invalid')

Finding sub strings:
-----------------------------
forward direction: backward direction:
find() rfind()
index() rindex()

1.find():s.find(substring)
Retunrs index of the first occurence of the given substring. If it is not available then we will get -1

2.index():
It is exactly same as find() method except that if the specified substring is not available then we will get ValueError.

Ex:
----
s = 'learning python is very 3asy'
print(s.find('e'))#1
print(s.index('e'))#1
print(s.find('z'))#-1
print(s.index('z'))#ValueError
print(s.rfind('e'))#24
print(s.rindex('e'))#24
print(s.rfind('z'))#-1
print(s.rindex('z'))#ValueError

Note:
Bydefault find() method can search total string. We can also specify the boundaries to search.

s = 'learning python is very easy'
print(s.find('e'))#1
print(s.find('e',3,10))#-1
print(s.find('e',3,22))#20

w.a.p to display all positions of substring in a given main string
----------------------------------------------------------------------------------------------
s = input('Enter main string:')
subs =input('Enter sub string:')
flag = False
pos = -1
n = len(s)
while True:
pos = s.find(subs,pos+1,n)
if pos == -1:
break
print('Found at position:',pos)
flag = True
if flag == False:
print('Not Found')

Replacing a string with another string:
----------------------------------------------------------
Syn:
s.replace(oldstring,newstring)
-->Inside s, every occurance of old string will be replaced with new string

s = 'learning python is difficult'
s1 = s.replace('difficult','easy')
print(s1)

Q.String object is immutable then how we can change the content by using replace() method?
Once we creates string object, we cant change the content. This non changable behaviour is nothing but immutability. If we are trying to change content by using any method, then with those changes a new object will be created and changes wont be happended in existing object.
Hence with replace() method also a new object got created but existing object wont be changed.

Ex:
s = 'abab'
s1 = s.replace('a','b')
print(s,'is available at:',id(s))
print(s1,'is available at:',id(s1))

Splitting of string:
---------------------------
-->We can split the given string according to specified separatpor by using split() method.
Syn: l = s.split(separator)
-->The default separator is space. The return type of split() method is list.

Ex:
s = 'learning python is very easy'
l = s.split()
print(l)
for i in l:
print(i)

Ex:
s = '10-02-2025'
l = s.split()
for i in l:
print(i)

Joining of strings:
----------------------------
We can join a group of strings(list or tuple) w.r.t the given separator.
Syn:
s = separator.join(group of strings)
Ex:
l = ['sunny','bunny','vinny']
print(':'.join(l))
print('-'.join(l))

Changing case of a string:
--------------------------------------
s = 'learning Python is very Easy'
print(s.lower())
print(s.upper())
print(s.swapcase())
print(s.title())
print(s.capitalize())

Checking starting and ending part of the string:
-----------------------------------------------------------------------
-->startswith()
-->endswith()

s = 'learning python is very easy'
print(s.startswith('learning'))#True
print(s.endswith('learning'))#False
print(s.endswith('easy'))#True


To check type of characters present in a string:
-----------------------------------------------------------------------
print('sunny123'.isalnum())
print('sunny123'.isalpha())
print('sunny'.isalpha())
print('sunny'.isdigit())
print('1234'.isdigit())
print('sunny'.islower())
print('sunny123'.islower())
print('SUNNY'.isupper())
print('Python Is Easy'.istitle())
print(' '.isspace())

Ex:
s = input('Enter any character:')
if s.isalnum():
print('Alpha numeric character')
if s.isalpha():
print('Alphabate character')
if s.islower():
print('Lower case alphabate char')
else:
print('Upper case alphabate char')
else:
print('It is a digit')
elif s.isspace():
print('It is a spcae')
else:
print('It is a special char.....')

Q.w.a.p to reverse the given string?
-----------------------------------------------------
1st way
-----------
s = input('Enter some string:')
print(s[::-1])

2nd way
------------
s = input('Enter some string:')
for x in reversed(s):
print(x,end='')

3rd way:
-------------
s = input('Enter some string:')
print(''.join(reversed(s)))

4th way:
-------------
s = input('Enter some string:')
i = len(s)-1
target = ''
while i >= 0:
target += s[i]
i -= 1
print(target)

Q.w.a.p to reverse order of words
i/p:'learning pythin is very easy'
i/p:'easy very is python learning'

s = input('Enter some string:')
l = s.split()
l1 = [ ]
i = len(l)-1
while i >= 0:
l1.append(l[i])
i -= 1
print(' '.join(l1))

Q.w.a.p to reverse internal content of each word
i/p:'learning python is very easy'
o/p:'gninrael nohtyp si yrev ysae'

s = input('Enter some string:')
l = s.split()
l1 = [ ]
i = 0
while i < len(l):
l1.append(l[i][::-1])
i += 1
print(' '.join(l1))

Q.w.a.p to print character at odd position and even position for the given string?
------------------------------------------------------------------------------------------------------------------------
i/p:'radhika'
even:'rdia
odd:'ahk'

s = input('Enter some string:')
print('Characters at even position:',s[0::2])
print('Characters at odd position:',s[1::2])



_______________________________________________________________________________________________________________________
Q.w.a.p to print character at odd position and even position for the given string?
------------------------------------------------------------------------------------------------------------------------
i/p:'radhika'
even:'rdia
odd:'ahk'

s = input('Enter some string:')
print('Characters at even position:',s[0::2])
print('Characters at odd position:',s[1::2])

or

s = input('Enter some string:')
i = 0
print('Characters at even position:')
while i < len(s):
print(s[i],end='')
i += 2
print()
i = 1
print('Characters at odd position:')
while i < len(s):
print(s[i],end='')
i += 2

w.a.p to merge characters of 2-strings into a single string by taking characters alternatively?
s1 = 'mahesh'
s2 = 'sunny'
o/p:'msauhnensyh'

s1 = input('Enter first string:')
s2 = input('Enter second string:')
output = ''
i,j = 0,0
while i < len(s1) or j < len(s2):
if i < len(s1):
output += s1[i]
i += 1
if j < len(s2):
output += s2[j]
j += 1
print(output)

w.a.p to sort the characters of the string first alphabates followed by numeric values.
-------------------------------------------------------------------------------------------------------------------------------
i/p:'B4A1D3'
o/p:'ABD134'

s = input('Enter some string:')
s1=s2=output = ''
for x in s:
if x.isalpha():
s1 += x
else:
s2 += x
for i in sorted(s1):
output += i
for i in sorted(s2):
output += i
print(output)

w.a.p for the following requirement.
i/p:'a4b3c2'
o/p:'aaaabbbcc'

s = input('Enter some string:')#a4b3c2
output = ''
for x in s:
if x.isalpha():
output += x
previous = x
else:
output += previous*(int(x)-1)
print(output)

w.a.p to perform the following activity
i/p:'a4k3b2'
o/p:'aeknbd'

s = input('Enter some string:')#a4k3b2
output = ''
for x in s:
if x.isalpha():
output += x
previous = x
else:
output += chr(ord(previous)+int(x))
print(output)

w.a.p to remove the duplicate chars from the given input string?
i/p:'ABCBABCDBCBABCBD'
o/p:'ABCD'

1st way
-----------
s = input('Enter some string:')
print(''.join(set(s)))

2nd way
------------
s = input('Enter some string:')
l = [ ]
for x in s:
if x not in l:
l.append(x)
print(''.join(l))

Comments

Popular posts from this blog

clinical_app

Workplace Backstabbing False Story Defense Kit

Python_While_Loop