7 String
7 String
7 String
String:
Any sequence of characters within double quotes or single quotes is
considered as a string.
Ex:
>>>s="HareKrishna"
>>>type(s)
<class ‘str’>
>>>ch='a'
>>>type(ch)
<class ‘str’>
In Python, string literals are enclosed in single quotes or double quotes.
Multiline strings: -
If you want to assign multiline strings then we use triple single quotes or triple
double quotes.
Ex:
>>>s='''krishna
Software
Solutions'''
>>>print(s)
s=’ramana’
0 1 2 3 4 5
r a m a n a
-6 -5 -4 -3 -2 -1
>>>s[2]
m
>>>s[-3]
a
>>>s[10]
IndexError: string index out of range.
Ex: Accept a string from the keyboard and display each character and its
positive and negative index.
s=input("Enter some string:")
i=0
for x in s:
print("The character at positive index { } and at negative index { } is { }"
.format(i,i-len(s),x))
i=i+1
Ex:
str="Learning python is very very easy"
b=int(input("Enter begin index:"))
e=int(input("Enter end index:"))
s=int(input("Enter step value:"))
print(str[b:e:s])
If it is negative then we have to consider in backward direction from begin to end+1.
In forward direction if end value is 0 then result is always empty.
In backward direction if end value is -1 then result is always empty.
Ex:
>>>s='abcdefghij'
>>>s[1:6:2] 'bdf'
>>>s[::1] 'abcdefghij'
>>>s[::-1] 'jihgfedcba'
>>>s[3:7:-1] ''
>>>s[7:4:-1] 'hgf'
>>>s[0:10000:1] 'abcdefghij'
>>>s[-4:1:-1] 'gfedc'
>>>s[-4:1:-2] 'gec'
>>>s[5:0:1] ''
>>>s[9:0:0] ValueError: slice step cannot be zero
>>>s[0:-10:-1] ''
>>>s[0:-11:-1] 'a'
>>>s[0:0:1] ''
>>>s[0:-9:-2] 'bdf'
>>>s[-5:-9:-2] 'fd'
>>>s[10:-1:-1] ''
>>>s[10000:2:-1] 'jihgfed'
Note: slice operator never raises IndexError.
4
Python
Note:
. To use + operator for strings, compulsory both arguments should be str type.
. To use * operator for strings, compulsory one argument should be str and other
argument should be int.
Ex:
str1 = 'Hello'
str2 ='World!'
# using +
print(str1 + str2)
# using *
print(str1 * 3)
print(2 * str1 )
len(): - This function is used to find the number of characters present in the string.
Ex:
s='krishna'
len(s) 7
5
Python
print(s[i],end='')
i=i-1
print("String1 is big")
else:
print("String2 is big")
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.
in operator returns True if the substring is available otherwise it returns False.
not in operator returns False if the substring is available otherwise it returns True.
Ex:
s='krishna'
print('i' in s) #True
print('b' in s) #False
Ex:
s=input("Enter main string:")
sub=input("Enter sub string:") if
sub in s:
print("substring is available in main string")
else:
print("substring is not available in main string")
7
Python
Syntax1:
String.find(substring)
Ex:
s="Learning python is very easy"
print(s.find('python')) #9
print(s.find('java')) #-1
Syntax2:
String.find(substring,start,end)
Ex:
s="Learning python is very easy"
print(s.find('h',2,10))
Syntax:
string.rindex(substring)
Ex:
s="Learning python is very easy"
print(s.rindex('h'))
Counting substrings:
count(): This function is used to counting the substring in the given string.
Syntax:
string.count(substring)
string.count(substring,begin,end)
Ex:
s='satish software solutions'
print(s.count('s'))
9
Python
Ex:
s='abababbabaab' sub='b'
print("The no of occurrences:",s.count(sub))
print("The no of occurrences:",s.count(sub,5,10))
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.
10
Python
Ex:
s="learning Python is very easy"
print(s.upper())
print(s.lower())
print(s.swapcase()) print(s.title())
print(s.capitalize())
11
Python
Ex:
s="learning Python is very easy"
print(s.startswith("learning"))
print(s.startswith("teaching"))
print(s.endswith("easy"))
12
Python
if s.islower():
print("Lower case character")
else:
print("Upper case character")
else:
print("Digit"
) elif s.isspace():
print("Space character")
else:
print("Non space special character")
target=' '
for I in range(len(s)-1,0,-1):
target=target+s[i]
print(target)
another way
s=input("Enter some string")
l=s.split();
l1=[]
for i in range(len(l)):
s1=s[i]
l1.append(s1[::-1])
print(l1)
out=' '.join(l1)
print(out)
another way
s=input("Enter some string")
l=s.split();
l1=[]
for x in l:
14
Python
l1.append(x[::-1])
out=' '.join(l1)
print(out)
another way
s=input("Enter some string") i=0
print("Character at even position:")
while(i<len(s)):
print(s[i],end=',')
i=i+2
print("Character at odd position:")
i=1
while(i<len(s)):
15
Python
print(s[i],end=',')
i=i+2
The above program works only for same length strings to solve the
following code.
s1=input("Enter first string:")
s2=input("Enter second string:") output=' '
i,j=0
while i<len(s1) or j<len(s2):
if i<len(s1):
output=output+s1[i]
i=i+1
if j<len(s2):
output=output+s2[j]
j=j+1
print(output)
16
Python
s2=s2+x
print(s1)
print(s2)
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)
#print(' '.join(sorted(s1)+ ' '.join(sorted(s2))
Ex: Enter string by character with number and display each character
specified number of times.
Input: a4c3b2
Output: aaaacccbb
s=input("Enter some string:")
output=' '
for x in s:
if x.isalpha():
previous=x
else:
output=output+(previous*(int(x))
print(output)
17
Python
Ex: Enter string display each number with specified alphabet character.
Input: a4k3b2
Output: aeknbd
chr(unicode) It provides character
ord(character) It provides Unicode value
output=output+chr(ord(previous)+int(x))
print(output)
Another way
s=input("Enter some string:")
output=' '
for x in s:
if x not in output:
output=output+x
print(output)
else:
19
Python
d[x]=1
for k,v in d.items():
print("{}={} Times".format(k,v))
20