0% found this document useful (0 votes)
13 views

STRING DATA TYPE

String data

Uploaded by

mg0129718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

STRING DATA TYPE

String data

Uploaded by

mg0129718
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

STRING DATA TYPE

String is a sequence of characters, which is enclosed between either single


(' ') or double quotes (" ") or triple quotes (''' ''' / """ """), python treats both
single, double quotes and triple quotes same. Strings are sequence of
characters, where each character has a unique position – id / index. The
indexes of a string begins from 0 to (length -1) in forward direction and from
-1 , -2, -3,………, -length in backward direction. Always the index value of a
string is represented in square bracket [ ].
For example:

Str = "ADITYA"

FORWARD DIRECTION 0 1 2 3 4 5
A D I T Y A
-6 -5 -4 -3 -2 -1 BACKWARD DIRECTION

Hence to access any location of a above given string one can write following
statement:

Str = "ADITYA"
print(Str[1])

output will be : D

Page 1 of 13
STRING DATA TYPE

Creating String
Creation of string in python is very easy.
e.g.

a=‘Computer Science'
b=“Informatics Practices“

Accessing String Elements e.g.

str='Computer Science'
print('str -', str)
print('str[0] -', str[0])
print('str[1:4] -', str[1:4])
print('str[2:] -', str[2:])
print('str*2-', str*2 )
print("str+'yes'-", str+'yes')

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
C o m p u t e r S c i e n c e
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

OUTPUT
str - Computer Science
str[0] - C
str[1:4] - omp
str[2:] - mputer Science
str*2 - Computer ScienceComputer Science
str+'yes'- Computer Scienceyes

Page 2 of 13
STRING DATA TYPE
Traversal of string: Traversing refers to iterating through the elements of a
string, one character at a time. The function len() is used to find the length
of a string, which includes white spaces also in between of defined string
within single/double/triple quote.

For Example:

str=input(“ Enter a string = ")


length=len(str)
print("============================")
print(" Length of the string ",str, " is = ", length)
i=0
for a in range(-1,(-length - 1), -1):
print(str[i],"\t",str[a])
i=i+1
print("============================")

Output:
Enter a string = Aditya
============================
Length of the string Aditya is = 6
A a
d y
i t
t i
y d
a A
============================

String comparison :
We can use (>,<,<=,<=,==,!=) to compare two strings .Python compares string
lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as "Maria" and str2 as "Manoj". The first two
characters from str1 and str2 (M and M ) are compared. As they are equal,
the second two characters are compared. Because they are also equal, the
third two characters (r and n ) are compared. And because 'r' has greater
ASCII value than ‘n', str1 is greater than str2.
Page 3 of 13
STRING DATA TYPE
e.g. program

print("Maria"=="Manoj")
print("Maria"!="Manoj")
print("Maria">"Manoj")
print("Maria">="Manoj")
print("Maria"<"Manoj")
print("Maria"<="Manoj")
print("Maria">"")

OUTPUT:
False
True
True
True
False
False
True

Updating Strings:

String value can be updated by reassigning another value in it.

e.g.

var1 = 'Comp Sc'


print(" The value of string before updating is = ", var1)
var1 = var1[:7] + ' with Python'
print ("Updated String is as = ",var1 )

OUTPUT :

The value of string before updating is = Comp Sc


Updated String is as = Comp Sc with Python

Page 4 of 13
STRING DATA TYPE
String Special Operators
e.g.
a="comp"
b="sc"

0 1 2 3 0 1
a= b=
c o m p s c

Operator Description Example


+ Concatenation–to add two strings a + b = compsc
* Replicate same string multiple times a*2 = compcomp
(Repetition)
[] Character of the string a[1] will give o
[:] Range Slice –Range string a[1:4] will give omp
in Membership check p in a will give 1
not in Membership check for non-availability M not in a will give 1
% Format the string

print ("My Subject is %s and class is %d" % ('Comp Sc', 11))

Format Symbol in string:


%s String conversion via str() prior to formatting
%i Signed decimal integer
%d Signed decimal integer
%u Unsigned decimal integer
%o Octal integer
%x Hexa-Decimal integer (lower case letters)
%X Hexa-Decimal integer (UPPER case letters)
%e Exponential notation (with lowercase 'e')
%E- Exponential notation (with UPPER case 'E')
%f Floating point real number
%c character
%G The shorter of %f and %E
Page 5 of 13
STRING DATA TYPE
String Slicing: String Slicing in Python refers to the act of extracting a
substring from a given string.
The syntax of a slice command is as follows:
string_name [start : end : step]
Note: The string value must be assigned to a variable before one can perform
slicing.
The syntax is similar to the range function, mostly used in loops.
range (start, stop, step)
It's important to understand the index values of each character before one
can perform slicing.
The index values, [both positive and negative respectively will be as follows:
Note: The special characters like spacing, symbols, etc. also have index
values.

Positive Indexing [ in Forward Direction]


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

P y t h o n P r o g r a m m i n g
-18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Negative Indexing [ in Backward Direction]


An example to demonstrate its working:
str1 ="Python Programming"
print(str1[:4])
print(str1[0:-5])
print(str1[3:5])
print(str1[-11:])

Output:
Pyth
Python Progra
ho
Programming

Page 6 of 13
STRING DATA TYPE

Example 2:

str1 ="Python Programming"


print(str1)
print(str1[:4])
print(str1[0:-5])
print(str1[3:5])
print(str1[-11:])
print(str1[0:8:2])
print(str1[: : -2])

Output :

Python Programming
Pyth
Python Progra
ho
Programming
Pto
gimroPnhy

Q.# Write a program to read a string and Display it in reverse order.

str1 = input ( " Enter a string = " )


print(" The Entered String is = ", str1)
print( "The ", str1, " in reverse order is as .... ")
l=len(str1)
for a in range(-1,(-l-1),-1):
print(str1[a],end=" ")

Output:
Enter a string = ABPS Renukoot
The Entered String is = ABPS Renukoot
The ABPS Renukoot in reverse order is as ....
tookuneR SPBA
Page 7 of 13
STRING DATA TYPE
Q.# Program to Enter a string and split each word and find its length.

# String Program
str= input(" Enter any string = ")
str1=str.split(' ')
for word in str1 :
print( word," ( ", len(word), ")")

Output:
Enter any string = ABPS Renukoot
ABPS ( 4 )
Renukoot ( 8 )

Q.# Program to enter a string with Punctuation and print them after
removing punctuation from the string.

punctuations = '''!()-[]{};:'"\,<>./?@$%^*_~'''
my_str = input ( " Enter any string : ")
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

no_punct=no_punct.lower()

# display the unpunctuated string


print(no_punct)

Output :

Enter any string : This # is My School, ABPS [Renukoot]


this # is my school abps renukoot

Page 8 of 13
STRING DATA TYPE
String functions and methods :

a=“comp”
b=“my comp”

Method Result Example


len() Returns the length of the string r=len(a) will be 4
str.capitalize() To capitalize the string r=a.capitalize() will be
“COMP”
str.title() Will return title case string
str.upper() Will return string in upper case r=a.upper() will be
“COMP”
str.lower() Will return string in lower case r=a.upper() will be
“comp”
str.count() will return the total count of a r=a.count(‘o’) will be 1
given element in a string

str.find(sub) To find the substring r=a.find(‘m’) will be 2


position(starts from 0 index)

str.replace() Return the string with replaced r=b.replace(‘my’,’your’)


sub strings will be ‘your comp’

str.index() Returns index position of r=a.index(‘om’) will be 1


substring

str.isalnum() String consists of only r=a.isalnum() will


alphanumeric characters (no returnTrue
symbols)

Page 9 of 13
STRING DATA TYPE

Method Result Example


str.isalpha() String consists of only
alphabetic characters (no
symbols)
str.islower() String’s alphabetic characters
are all lower case
str.isnumeric() String consists of only numeric
characters
str.isspace() String consists of only
whitespace characters
str.istitle() String is in title case

str.isupper() String’s alphabetic characters


are all upper case

str.lstrip(char) Returns a copy of the string with b=‘**comp’;


str.rstrip(char) leading/trailing characters r=b.lstrin() will be ‘comp’
removed
str.strip(char) Removes specific character from
leading and trailing position
str.split() Returns list of strings as splitted b=‘my comp’;
r=b.split() will be
[‘my’,‘comp’]

str.partition() Partition the string on first b=‘my comp’;


occurrence of substring r=b.partition(‘comp’) will
be [‘my’,‘comp

Page 10 of 13
STRING DATA TYPE

Searching for Substrings :


METHOD NAME METHODS DESCRIPTION:
e.g. program
endswith(s1: str): bool Returns True if strings ends
with substring s1 s = "welcome to python"
print(s.endswith("thon"))
startswith(s1: str): bool Returns True if strings
print(s.startswith("good"))
starts with substring s1
print(s.find("come"))
count(substring): int Returns number of print(s.find("become"))
occurrences of substring the print(s.rfind("o"))
string print(s.count("o"))
find(s1): int Returns lowest index from
OUTPUT
where s1 starts in the
string, if string not found True
returns -1 False
3
rfind(s1): int Returns highest index from -1
where s1 starts in the 15
string, if string not found 3
returns -1

Q.# Program to check whether given string is Palindrome or/not, by


using string slicing.

s=input(" Enter a string = ")


if(s==s[: : -1]):
print(" The given string", s, " is a palindrome string")
else:
print(" The given string", s, " is not a palindrome string")

Output:
Enter a string = Madam
The given string Madam is not a palindrome string

Enter a string = madam


The given string madam is a palindrome string

Page 11 of 13
STRING DATA TYPE

# Program to check whether given string is palindrome or/not without


using string slicing.

st= input( " Enter any string = ")


L= len(st)
st1=""
print(" The entered string is = " ,st, " and its length is = ",L )
Flag= 0
mid=int(L/2)
for i in range (0, mid+1):
if(st[i]==st[L-i-1]):
Flag=1
else :
Flag=0
if(Flag==1):
print(" The entered string ",st, " is a Palindrome ")
else:
print(" The entered string ",st, " is Not a Palindrome ")

output :

Enter any string = malayalam

The entered string is = malayalam and its length is = 9

The entered string malayalam is a Palindrome

Page 12 of 13
STRING DATA TYPE
# Program to check whether given string is palindrome or/not by
revising the string

st= input( " Enter any string = ")


L1= len(st)
st1=""
print(" The entered string is = " ,st, " and it's length is = ",L1 )
for i in st:
st1=i + st1
L2=len(st1)
print(" The reversed string is = " ,st1, " and it's length is = ",L2 )
if (st == st1):
print(" The given string ", st, " is a Palindrome")
else:
print(" The given string ", st, " is not a Palindrome")

Output:
Enter any string = madam
The entered string is = madam and it's length is = 5
The reversed string is = madam and it's length is = 5
The given string madam is a Palindrome

#Python Program to calculate the number of digits and letters in a


string
string=input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)
Output:
Enter string : ABPS Renukoot-231217
The number of digits is: 6
The number of characters is: 20
Page 13 of 13

You might also like