String Data Type
A string is a sequence of characters.
String Data Type
str1="hello"
print(type(str1))
Ans: <class ‘str’>
str2='123'
print(type(str2))
Ans: <class ‘str’>
str2='123'
ch=int(str2)
print(type(ch))
Ans: <class ‘int’>
Adding and Concatenation using ‘+’
Adding to the two string using the ‘+’
str1="hello"
str2='paris'
add1=str1+str2
print(add1)
Ans: Hello Paris
Adding to the two string using the ‘+’ but even the numeric values here is also a string adding any numeric value to it will cause error.
str2='123'
ch=str2+1
print(ch)
Ans: Error String type cannot add any numeric 1.
Before adding any value first it needs to change its type ‘int’, then any addition can take place.
str2='123'
ch=int(str2)+1
print(ch)
Ans: 124
s=’1’+’1′
print(s)
Ans: ’11’
s=’1’+’1′
print(int(s)+1)
Ans: True
Comparison
'Hello'=='Hello'
Ans: True
'Hello'=='hello'
Ans: False
'1'==1
Ans: False
'1'=='1'
Ans: True
Array
fruit='apple'
print(fruit[1])
Ans: ‘p’
fruit='banana'
x=2
print(fruit[x+2])
Ans: ‘n’
For Loop
fruit='apple'
for i in range(0,5):
print(fruit[i])
Ans:
a
p
p
l
e
fruit='apple'
for i in range(0,6):
print(fruit[i])
Ans:
a
p
p
l
e
Error: No index value
for i in range(0,len(fruit)):
print(fruit[i])
Ans:
a
p
p
l
e
fruit='apple'
for letter in fruit:
print(letter)
Ans:
a
p
p
l
e
To find the response of array in the one line then ‘sys’ library can be used
import sys
for i in range(0,len(fruit)):
sys.stdout.write(fruit[i])
Ans: apple
While Loop with the len function
fruit='apple'
i=0
while i<len(fruit):
ch=fruit[i]
print(i,ch)
i=i+1
Ans:
0 a
1 p
2 p
3 l
4 e
word='banana'
count=0
for letter in word:
if letter=='a':
count=count+1
print(count)
Ans:
1
2
3
String Functions
Length of the string
fruit='apple'
len(fruit)
Ans: 5
Creating Arrays from the line
str1 = "I love my country"
str1[0:]
Ans: 'I love my country'
str1[0:10]
Ans: 'I love my'
str1[3:4]
Ans: 'o'