String

  • Strings are a sequence of characters.
  • It is used to store text.Strings in Python can be enclosed in single quotes or double quotes, or even in triple quotes.
  • Once a value is given to a string, we cannot change the value of a character present at a particular position.
  • Python provides many built in functions to help the programmers to handle strings.
  • Strings in Python are non-mutable.
  • The negative index denotes the characters from the right hand.
  • Strings are iterable objects.

>>> len()

Explanation:

The function returns the number of characters in a string. 

>>> capitalize()

Explanation:

The function capitalizes the first character of the string. Note that only the first character will be capitalized. If one wants to capitalize the first characters of all the words in the string the title() function can be used.

find

Usage:

>>><name of the string>.find(<parameter(s)>)

Explanation:

The location of a given sub-string in a given string can be found by using the function find. Also, if the location of a sub-string after a particular position (and before a particular index) is to be determined, then three arguments can be passed to the function: the sub-string, initial index, and the final index. 

>>> str2.find(‘ha’) 0 >>> >>> str2.find(‘ha’,3,len(str2)) 7

count

Usage:

>>><name of the string>.count(<parameter(s)>)

Explanation:

The number of occurrences of a particular substring can be found with the count function. The function takes three arguments: the sub-string, the initial index, and the final index.

Endswith

Usage: <name of the string>.endswith(<parameter(s)>)

Explanation:

We can determine if a string ends with a particular sub-string using the endswith() function. The function returns a 'True' if the given string ends with the given sub-string, otherwise it returns a 'False'.

Encode

Usage: <name of the string>.encode(<parameter(s)>) >>>

Explanation:

Python provides a function to encode a given string in various formats. The function is encode. It takes two arguments: encoding=<value> and errors=<value>. 

Decode

Usage:

>>><name of the string>.decode(<parameter(s)>)

Explanation:

The function returns the decoded string.

How to define multi-line String literals:
We can define multi-line String literals by using triple single or double quotes.
Eg:

s=”’cloud
software
solutions”’
We can also use triple quotes to use single quotes or double quotes as symbol inside String literal.


How to access characters of a String:


We can access characters of a string by using the following ways.

  1. By using index
  2. By using slice operator
  3. 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)
    Eg:
    s=’cloud’
    diagram
    Eg:

s=’cloud’
s[0]
‘c’

s[10]
IndexError: string index out of range
Note: If we are trying to access characters of a string with out of range index then we will get
error saying : IndexError

Accessing characters by using slice operator:

Syntax: s[bEginindex:endindex:step]
bEginindex:From where we have to consider slice(substring)
endindex: We have to terminate the slice(substring) at endindex-1
step: incremented value
Note: If we are not specifying bEgin index then it will consider from bEginning of the string.
If we are not specifying end index then it will consider up to end of the string
The default value for step is 1
Eg:
1) >>> s=”Learning Python is very very easy!!!”
2) >>> s[1:7:1]
3) ‘earnin’

Behaviour of slice operator:

s[bEgin:end:step]
step value can be either +ve or –ve
if +ve then it should be forward direction(left to right) and we have to consider bEgin to end-1
if -ve then it should be backward direction(right to left) and we have to consider bEgin to end+1

Programs

Write a program to traverse a string.

Solution: 

str1= input('Enter a string\t:')

for i in str1:

print('Character \t:',i)

Write a program to find the length of the string entered by the user.

name=input('Enter your name\t');

length=0 for i in name:

length=length +1

print('The length of ',name,' is ',length)

Consider you have to enter a string and displace two characters to the right.How will you do it?

str1=input('Enter the string\t:')

i=0

str2=""

while i<len(str1):

str2[i]=str1[(i+2)%len(str1)]

print(str2)

Write a program to access each character of string in forward and backward direction by using while loop?

1) s=”Learning Python is very easy !!!”
2) n=len(s)
3) i=0
4) print(“Forward direction”)
5) while i=-n:
11) print(s[i],end=’ ‘)
12) i=i-1

Removing spaces from the string:

We can use the following 3 methods

  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

find():

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

Note: By default find() method can search total string. We can also specify the boundaries to search.
s.find(substring,bEgin,end)
It will always search from bEgin index to end-1 index

index() method:

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

Counting substring in the given String:

We can find the number of occurrences of substring present in the given string by using count() method.

  1. s.count(substring) ==> It will search through out the string
  2. s.count(substring, bEgin, end) ===> It will search from bEgin index to end-1 index
    Eg:
    1) s=”abcab”
    2) print(s.count(‘a’))

Replacing a string with another string:

s.replace(oldstring,newstring)

inside s, every occurrence of oldstring will be replaced with newstring.
Eg1:
s=”Learning Python is very difficult”
s1=s.replace(“difficult”,”easy”)
print(s1)

Program to reverse order of words.

1) input: Learning java is very Easy
2) output: Easy Very is java Learning
3)
4) s=input(“Enter Some String:”)
5) l=s.split()
6) l1=[]
7) i=len(l)-1
8) while i>=0:
9) l1.append(l[i])
10) i=i-1
11) output=’ ‘.join(l1)
12) print(output)

String objects are immutable then how we can change the content by using replace() method.

If we are trying to change the content by using any method, then with
those changes a new object will be created and changes won’t be happend in existing object.

s=”abab”
s1=s.replace(“b”,”c”)
print(s,”is available at :”,id(s))

Write a program to print characters at odd position and even position for the given String?

s=input(“Enter Some String:”)
print(“Characters at Even Position:”,s[0::2])
print(“Characters at Odd Position:”,s[1::2])

Write a program to reverse the given String

input: vikas
output:sakiv


1st Way:
s=input(“Enter Some String:”)
print(s[::-1])


2nd Way:
s=input(“Enter Some String:”)
print(”.join(reversed(s)))


3rd Way:
s=input(“Enter Some String:”)
i=len(s)-1
target=”
while i>=0:
target=target+s[i]
i=i-1
print(target)

Program to display all positions of substring in a given main string

1) s=input(“Enter main string:”)
2) subs=input(“Enter sub string:”)
3) flag=False
4) pos=-1
5) n=len(s)
6) while True:
7) pos=s.find(subs,pos+1,n)
8) if pos==-1:
9) break
10) print(“Found at position”,pos)
11) flag=True
12) if flag==False:
13) print(“Not Found”)

Write a program to remove duplicate characters from the given input string?

1) s=input(“Enter Some String:”)
2) l=[]
3) for x in s:
4) if x not in l:
5) l.append(x)
6) output=”.join(l)
7) print(output)

OBJECTIVE QUIZ

If str1=’Ram’, what is the output of print(str1[4])

i

\0

Exception is raised

None of the above

Answer:
(c)

If str1=’Rani’, what is the output of print(str1[-3])

“a”

“H”

Exception is raised

None of the above

Answer:
(a)

What is the output of “vikas”==“VIKAS”

True

False

An exception is raised

None of the above

Answer:
(b)

What is the output of ‘b’!=’B’

True

False

Exception is raised

None of the above

Answer:
(a)

What is the output of ’56’>’98’

True

False

An exception is raised

None of the above

Answer:
(b)

Which of the following helps to find the ASCII value of “B”?

ord(‘B’)

chr(‘C’)

both

None of the above

Answer:
(a)

Which of the following helps to find the character represented by ASCII value 57?

ord(57)

chr(57)

Both

None of the above

Answer:
(b)

What are ‘in’ and ‘not in’, in Python?

Relational operators

Membership operators

Concatenation operators

None of the above

Answer:
(b)

What is the output of ‘A’ + ‘B’

‘A+B’

‘AB’

131

None of the above

Answer:
(b)

What is the output of 3*’B’

‘3b’

Character corresponding to the ascii value 65 × 3?

‘BBB’

None of the above

Answer:
(c)

Which function capitalizes the first character of a given string?

capitilize()

titlecase()

toupper()

None of the above

Answer:
(a)

The find() function in Python takes

1 argument

3 arguments

Both

None of the above

Answer:
(c)

If str1=’vika’, then what would be the output of isalnum()?

True

False

Exception is raised

None of the above

Answer:
(b)

If str1=’ram3′, then what would be the output of str1.asalnum()?

True

False

Exception is raised

None of the above

Answer:
(d)

If str1=’vikas feb’, then what would be the output of str1.asalnum()?

True

False

Exception is raised

None of the above

Answer:
(d)

If str1=’123h’, then what would be the output of str1.isdigit()?

True

False

Exception is raised

None of the above

Answer:
(b)

Which function checks whether all the characters in a given string are in lower case?

lower()

islower()

istitle()

None of the above

Answer:
(b)

Which function checks whether all the characters in a given string are in upper case?

upper()

isupper()

istitle()

None of the above

Answer:
(b)

Which function removes the whitespaces from the right hand of a given string?

rstrip()

strip()

lstrip()

None of the above

Answer:
(a)

Which of the following functions convert a given string into a list of words?

split()

break()

breakup()

None of the above

Answer:
(a)

Which of the following helps in breaking a string into two substrings of desirable length?

Slicing

Splitting

Both

None of the above

Answer:
(a)

Which of the following functions combines the strings given as the argument?

Split

Join

Slice

None of the above

Answer:
(b)