Python: Working with Strings
-
Inbuilt functions
-
'str' is most commonly used data type.
-
In python there is no 'char' data type.
-
ch=’a’ is treated as str type only not char type.
-
We can create string object using ‘ ‘ or ‘’ ‘’
Example
s=’knowcubs’
or
s=”knowcubs”
Multi line string literals :
If we need to write multi line string literals we can use Triple quotes (triple single quotes or triple double quotes).
Example
Single quotes as a symbol
There are 2 ways to use single quotes as a symbol
1. use double quotes to represent string.
2. use \(backslash symbol)
Double quotes as a symbol
There are 2 ways to use double quotes as a symbol
1. use single quotes to represent string.
2. use \(backslash symbol)
How to access characters of the string
1. By using index
In python 2 types of index are possible means we can access a string from both side left to right and right to left.
i) +ve index(from left to right)
ii) -ve index(from right to left)
i) +ve index(from left to right)
ii) -ve index(from right to left)
If we try to access out of range Index.
#Write a program to accept some string and print all character with index.
2. By using slice operator
Slice Operator is used to divide string into smaller substrings
Form:1 S[begin:end] - returns substring from begin index to end-1 index.
Example
s=’knowcubs’
s[1:7]==>nowcub
s[2:7]==>owcub
Note 1: End index is not mandatory, if you are not specifying end by default end value is end of the string.
s[1:]==>nowcubs
Note 2: begin index is also not mandatory, if you are not specifying begin by default begin value is start of the string.
s[:7]==>knowcub
Note3: begin and end both are not mandatory to specify.
Form:2 S[begin:end:step]
By default value of step is 1. Step value can be either +ve or -ve
If +ve then it will be forward direction (left to right)
If -ve then it will be backward direction (right to left)
If +ve forward direction from begin to end-1
If -ve backward direction from begin to end+1
Example
s=’0123456789’
S[2:8:1] =>234567
S[2:8:-1] =>empty output
S[2:8:0] =>slice step value cannot be 0
S[-1:-6:-1]=>98765
S[2:-5:1]=>234
S[1:6:-2]=>empty string
S[0:-5:-5]=>empty
#Reverse a string using slice operator
Mathematical Operation on string object
1. + (Concatenation Operator )
2.*(Repetition Operator )
Note: For repetition operator first argument must be string and second argument must be int otherwise you will get syntax error.
Inbuilt functions in string
len(): it is use to find no of characters present in a list.
Example
# WAP to access each character of string in forward direction and backward direction
1. By using slice operator
2. By using while loop
Membership operators in string
in
not in
Example
s=”knowcubs”
print(‘c’ in s)#True
print(‘z’ in s)#False
#WAP to check substring is available in string or not
Comparison operators in string
>, >=, <, <=
Comparison takes place based on dictionary order.
Equality operators
==, !=
In general '==' operator meant for content operator
Example
Methods to remove spaces
lstrip()
to remove spaces present at left side or beginning of the string.
rstrip()
to remove spaces present at right side or end of the string.
strip()
strip is used to remove spaces from beginning and end both side.
Example
Finding substring
To find whether or not a substring is present in string, following operators are used:
-
find()
-
rfind()
-
index()
-
rindex()
1. find()
find(substring): find substring from beginning of the string.
If the substring is available then find() method returns index of first occurrence of the substring otherwise it returns -1.
rfind(substring): find substring from backside (right side) of the string.
If the substring is available then rfind() method returns index of first occurrence from right side of the substring otherise it retruns -1.
Example
find(substring,begin,end): Find substring from beginning to end-1 of the string. By default begin value is 0 and end value is length-1.
rfind(substring,begin,end): Find substring from end of the string. By default begin value is 0 and end value is length-1.
2. index()
same as find() method except that if the specified substring is not available you will get value error not –1.
rindex()
same as rfind() method except that if the specified substring is not available we will get value error not –1.
Counting substrings in the given string
count(substring): used to find number of times the specified substring is present in the given string.
count(substring,begin,end): similar to count() but in this we can specify begin and end index also. By default begin value is 0 and end value is length-1.
Example
Replacing a string with another string
replace(oldstring,newstring): replace a string with specified string.
Example
When we use replace() method it does not affect the existing object, instead it creates new object.
Example
Splitting of string
split(): used to split a string into parts based on separator.
Default separator is space (‘ ’). Splited string will be stored in a list.
Example
#Split a date string based on separator ‘-’
rsplit(): It gives in split reverse direction (from right).
Example: If we want maximum 4 substrings from right.
Joining of strings
Join(): it joins each element of list by a string separator and returns the concated string.
Example
Changing case of a string
upper(): To convert to upper case
lower(): To convert to lower case
swapcase(): To convert lower to upper and upper to lower
title(): Every word start with upper case.
capitalize(): In the total string first character is upper case and other one is lower case.
Example
Checking Starting and Ending part of the String
startswith(substring)
endswith(substring)
Example
#To print characters at odd position and even position for the given string.
1st method:
2nd method
Check type of characters present in a string
isalnum(): to check characters are alphanumeric or not {A-Z ,a-z,0-9}
isalpha():to check characters are alphabetic or not {A-Z,a-z}
isdigit(): to check characters are digit or not {0-9}
islower(): to check characters are lowercase or not.
isupper(): to check characters are in upper case or not.
istitle(): to check characters are in title case or not
isspace(): to check character is space or not.
Example
print(‘knowcubs786’.isalnum() #True
print(‘knowcubs786’.isalpha() #False
print(‘knowcubs’.isalpha() #True
print(‘knowcubs’.islower() #True
print(‘knowcubs’.isupper() #False
print(‘Indian Space Research Organisation’.istitle() #True
print(‘Indian Space Research Organisation’.isspace() #True
#WAP to separate alphabets and digits
#Input: a4b3c2 Output: aaaabbbcc
#Input: a4k3b2 Output: aeknbd
#WAP to reverse string
1st method:
2nd method:
3rd method:
#WAP to reverse internal content of each word of a string.