String Data Type - Unit-3
String Data Type - Unit-3
DATA TYPE
The most commonly used object in any project and in any programming language is String
only. Hence we should aware complete information about String data type.
What is String?
Any sequence of characters within either single quotes or double quotes is considered as a
String.
Syntax:
s = 'hello'
s ="world"
Note: In most of other languges like C, C++, Java, a single character with in single quotes
is treated as char data type value. But in Python we are not having char data type.Hence it
is treated as String only.
Eg:
>>> ch = 'a'
>>> type(ch)
<class 'str'>
Eg:
>>> s = '''
welcome to
python”””
We can also use triple quotes to use single quotes or double quotes as symbol inside
String literal.
1) >>> s='hello'
2) >>> s[0]
3) 'h’
4) >>> s[4]
5) '0'
6) >>> s[-1]
7) '0'
8) >>> s[10]
9) 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
Q) Write a Program to Accept some String from the Keyboard and display its
Characters by Index wise (both Positive and Negative Index)
test.py:
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.
***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.
In Forward Direction:
default value for bEgin: 0
default value for end: length of string
default value for step: +1
In Backward Direction:
default value for bEgin: -1
default value for end: -(length of string+1)
Note: Either forward or backward direction, we can take both +ve and -ve values for
bEgin and end index.
print("hello"+"world") helloworld
print("hello"*2) hellohello
Note:
1) To use + operator for Strings, compulsory both arguments should be str type.
2) To use * operator for Strings, compulsory one argument should be str and other
argument should be int.
Alternative ways:
1) s = "Learning Python is very easy !!!"
2) print("Forward direction")
3) for i in s:
4) print(i,end=' ')
5) print("Forward direction")
6) for i in s[::]:
7) print(i,end=' ')
8)
9) print("Backward direction")
10) for i in s[::-1]:
11) print(i,end=' ')
Checking Membership:
We can check whether the character or string is the member of another string or not by
using in and not in operators
s = 'hello'
print('h' in s) True
print('z' in s) False
Output:
D:\python_classes>py test.py
Enter main string: welcome to python
Enter sub string:python
durga is found in main string
D:\python_classes>py test.py
Enter main string:welcome to python
Enter sub string:hello
python is not found in main string
Comparison of Strings:
We can use comparison operators (<, <=, >, >=) and equality operators (==, !=) for
strings.
Comparison will be performed based on alphabetical order.
Output:
D:\python_classes>py test.py
Enter first string:hello
Enter Second string: hello
Both strings are equal
D:\python_classes>py test.py
Enter first string:hello
Enter Second string:welcome to python
First String is less than Second String
D:\python_classes>py test.py
Enter first string:welcome
Enter Second string:hello
First String is greater than Second String
Finding Substrings:
We can use the following 4 methods
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.
1) s="welcometopython3"
2) print(s.find('0'))#4
3) print(s.find('p',7,15))#9
4) print(s.find('z',7,15))#-1
index():
index() method is exactly same as find() method except that if the specified substring is
not available then we will get ValueError.
Output:
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:python
substring found
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:java
substring not found
Output:
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:bb
Found at position 1
Output:
6
4
2
Eg 1:
s = "Learning Python is very difficult"
s1 = s.replace("difficult","easy")
print(s1)
Output: bbbbbbbbbbbbbb
Splitting of Strings:
We can split the given string according to specified seperator by using split() method.
l = s.split(seperator)
The default seperator is space. The return type of split() method is List.
1) s="hello world"
2) l=s.split()
3) for x in l:
4) print(x)
Output:
Hello
world
1) s="22-02-2018"
2) l=s.split('-')
3) for x in l:
4) print(x)
Output:
22
02
2018
Joining of Strings:
We can join a Group of Strings (List OR Tuple) wrt the given Seperator.
s = seperator.join(group of strings)
Eg 1:
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s)
Output: sunny-bunny-chinny
Eg 2:
l = ['hyderabad', 'singapore', 'london', 'dubai']
s = ':'.join(l)
print(s)
Output: hyderabad:singapore:london:dubai
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
Eg:
1) print('Hello786'.isalnum()) True
2) print('hello786'.isalpha()) False
3) print('hello'.isalpha()) True
4) print('hello'.isdigit()) False
5) print('786786'.isdigit()) True
6) print('abc'.islower()) True
7) print('Abc'.islower()) False
8) print('abc123'.islower()) True
9) print('ABC'.isupper()) True
10) print('Learning python is Easy'.istitle()) False
11) print('Learning Python Is Easy'.istitle()) True
12) print(' '.isspace()) True
Demo Program:
D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character
it is a digit
D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character
Alphabet character
Lower case alphabet character
D:\python_classes>py test.py
Enter any character:$
Non Space Special Character
D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character
1) name = 'aakash'
2) salary = 10000
3) age = 48
4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
‘aakash 's salary is 10000 and his ageis48
aakash 's salary is 10000 and his age is48
aakash 's salary is 10000 and his age is 48
Important Programs regarding String Concept
1st Way:
1) s = input("Enter Some String:")
2) print(s[::-1])
2nd Way:
1) s = input("Enter Some String:")
2) print(''.join(reversed(s)))
3rd Way:
1) s = input("Enter Some String:")
2) i=len(s)-1
3) target=''
4) while i>=0:
5) target=target+s[i]
6) i=i-1
7) print(target)
1st Way:
s = input("Enter Some String:")
print("Characters at Even Position:",s[0::2])
print("Characters at Odd Position:",s[1::2])
2nd Way:
1) s=input("Enter Some String:")
2) i=0
3) print("Characters at Even Position:")
4) while i< len(s):
5) print(s[i],end=',')
6) i=i+2
7) print()
8) print("Characters at Odd Position:")
9) i=1
10) while i< len(s):
11) print(s[i],end=',')
12) i=i+2
Q4) Program to Merge Characters of 2 Strings into a Single
String by taking Characters alternatively
1) s1=input("Enter First String:")
2) s2=input("Enter Second String:")
3) output=''”
4) i,j=0,0
5) while i<len(s1) or j<len(s2):
6) if i<len(s1):
7) output=output+s1[i]
8) i+=1
9) if j<len(s2):
10) output=output+s2[j]
11) j+=1
12) print(output)
Output:
Enter First String:hello
Enter Second String:world
hweolrllod
Output:
D:\durgaclasses>py test.py
Enter Some String:one two three four five six seven
Original String: one two three four five six seven
output String: one owt three ruof five xis seven
Formatting the Strings:
֍ We can format the strings with variable values by using replacement operator {} and
format() method.
֍ The main objective of format() method to format string into meaningful output form.
1) name = 'ankit'
2) salary = 10000
3) age = 48
4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
ankit 's salary is 10000 and his age is 48
ankit 's salary is 10000 and his age is 48
ankit 's salary is 10000 and his age is 48
d Decimal IntEger
f Fixed point number(float).The default precision is 6
b Binary format
o Octal Format
x Hexa Decimal Format (Lower case)
X Hexa Decimal Format (Upper case)
Eg-1:
Output:
The intEger number is: 123
The intEger number is: 123
The intEger number is: 123
The intEger number is: 00123
Eg-2:
Output:
The float number is: 123.4567
The float number is: 123.456700
The float number is: 123.457
The float number is: 0123.457
The float number is: 0123.450
The float number is: 786786123.450
Note:
֍ {:08.3f}
֍ Total positions should be minimum 8.
֍ After decimal point exactly 3 digits are allowed.If it is less then 0s will be placed in the
last positions
֍ If total number is < 8 positions then 0 will be placed in MSBs
֍ If total number is >8 positions then all intEgral digits will be considered.
֍ The extra digits we can take only 0
1) print("Binary Form:{0:b}".format(153))
2) print("Octal Form:{0:o}".format(153))
3) print("Hexa decimal Form:{0:x}".format(154))
4) print("Hexa decimal Form:{0:X}".format(154))
Output:
Binary Form:10011001
Octal Form:231
Hexa decimal Form:9a
Hexa decimal Form:9A
Note: We can represent only int values in binary, octal and hexadecimal and it is not
possible for float values.
Note:
1) {:5d} It takes an intEger argument and assigns a minimum width of 5.
2) {:8.3f} It takes a float argument and assigns a minimum width of 8 including "." and
after decimal point excatly 3 digits are allowed with round operation if required
3) {:05d} The blank places can be filled with 0. In this place only 0 allowed.
Output:
int value with sign:+123
int value with sign:-123
float value with sign:+123.456000
float value with sign:-123.456000
Ex:
1) print("{:5d}".format(12))
2) print("{:<5d}".format(12))
3) print("{:<05d}".format(12))
4) print("{:>5d}".format(12))
5) print("{:>05d}".format(12))
6) print("{:^5d}".format(12))
7) print("{:=5d}".format(-12))
8) print("{:^10.3f}".format(12.23456))
9) print("{:=8.3f}".format(-12.23456))
Output:
12
12
12000
12
00012
12
-12
12.235
- 12.235