Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python-strings

This document provides an overview of strings in Python, detailing their characteristics, such as being immutable and indexed. It includes examples of string manipulation, including slicing, looping through strings, and built-in string methods. Additionally, it covers string formatting, escape sequences, and how to check for specific phrases within strings.

Uploaded by

Anitha Nagesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python-strings

This document provides an overview of strings in Python, detailing their characteristics, such as being immutable and indexed. It includes examples of string manipulation, including slicing, looping through strings, and built-in string methods. Additionally, it covers string formatting, escape sequences, and how to check for specific phrases within strings.

Uploaded by

Anitha Nagesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PYTHON APPLICATION PROGRAMMING -18EC646

MODULE 2

STRINGS

Prof. Krishnananda L
Department of ECE
Govt Engineering College
Mosalehosahalli, Hassan
STRINGS:

 A string is a group/ a sequence of characters. Since Python has no provision


for arrays, we simply use strings. We use a pair of single or double quotes to
declare a string.
 Strings is “sequence data type” in python: meaning – its ordered, elements
can be accessed using positional index Position
 String may contain alphabets, numerals, special characters or a combination
of all these.
 String is a sequence of characters represented in Unicode. Each character of
a string corresponds to an index number, starting with zero.
 Strings are “immutable” i.e., once defined, the string literals cannot be
reassigned directly.
 Python supports positive indexing of string starting from the beginning of the
string as well as negative indexing of string starting from the end of the
string . 2

 Python has a vast library having built-in methods to operate on strings


STRING EXAMPLE PROGRAM:

 Example 2  Example 3
 Example1
 INPUT:  INPUT:
 INPUT:
>>>a = 'Hello world’
>>>a = 'Hello world’
>>> print(‘Hello world’) >>>a[0]=‘M’
>>>print(a)
 OUTPUT:  OUTPUT:
 OUTPUT:
Hello world  Traceback (most recent call last):
Hello world File "<pyshell#19>", line 1, in
 INPUT: <module>
 INPUT:
>>> print(“Hello world@@”) a[0]='M'
>>>a = 'Hello world’
 OUTPUT: TypeError: 'str' object does not
>>> a support item assignment
Hello world@@
 OUTPUT: Note: String is “immutable” Not 3
possible to change the elements of the
‘Hello world’ string through assignment operator
POSITIVE AND NEGATIVE INDEXING OF A STRING:

 Positive indexing:  Negative indexing:


 INPUT: >>>a = "Hello, World!"  INPUT:
>>>print(a[7])
>>>a = ‘Hello world’ W >>> a = 'Hello World’
print(a[1]) >>> print(a[-1])
 OUTPUT:  OUTPUT:
e d

4
MULTILINE STRINGS:

 using three quotes:  Using three single quotes:


 INPUT:  INPUT:
a = “””Python is an interpreted high-level a = ‘’’Python is an interpreted high-level
general-purpose programming language. Python's general-purpose programming language. Python's
design philosophy emphasizes code readability design philosophy emphasizes code readability
with significant indentation.””” with significant indentation.’’’
print(a) print(a)
 OUTPUT:  OUTPUT:
Python is an interpreted high-level general- Python is an interpreted high-level general-
purpose programming language. Python's design purpose programming language. Python's design
philosophy emphasizes code readability with philosophy emphasizes code readability with
significant indentation. significant indentation. 5
LOOPING THROUGH A STRING:

str = "welcome to Python class "


 For loop:  While loop:
for k in str:
 INPUT:  INPUT: if k == 'P':
for x in “hello": st=“hello" break
print(k, end=' ')
print(x) i=0
Output:
 OUTPUT: while i<len(st): welcome to
h print(st[i], end=‘ ’)) str = "welcome to Python class "
e i=i+1 for k in str:
print(k, end=' ')
l  OUTPUT:
if k == 'P':
l hello break
6
Output:
o
welcome to P
LOOPING CONTD…

# prints all letters except 'a' and 'k'


## to print names of the list
## illustration of continue
print ("illustration of for loop--- printing names
## illustration of logical operators
from list")
names=["anand", "arun", "akshata", "anusha"]
i=0
for i in names:
str1 = ‘all is well'
print ("hello " , i)
print ("COMPLETED ---")
while i < len(str1):
Current Letter : a if str1[i] == ‘s' or str1[i] == ‘l':
Current Letter : i += 1
Current Letter : i continue
Current Letter : print('Current Letter :', str1[i])
Current Letter : w i += 1
Current Letter : e 7
LOOPING CONTD..
""" program to illustrate for loop and multiple if statements
with string to count the occurrence of each vowel """ print ("Given string is %s " %(txt))
print ("total \'A\' or \'a\' in the string is: %d " %(counta))
txt='HELLO how are you? I am fine'
counta, counte, counti, counto, countu=0,0,0,0,0
print ("total \'E\' or \'e\' in the string is: %d " %(counte))
for k in txt: print ("total \'I\' or \'i\' in the string is: %d " %(counti))
if k=='a' or k=='A': print ("total \'O\' or \'0\' in the string is: %d " %(counto))
counta+=1 print ("total \'U\' or \'u\' in the string is: %d " %(countu))
if k=='e' or k=='E':
counte+=1 Output:
if k=='i' or k==‘’I’: Given string is HELLO how are you? I am fine
counti+=1 total 'A' or 'a' in the string is: 2
if k=='o' or k =='O': total 'E' or 'e' in the string is: 3
counto+=1 total 'I' or 'i' in the string is: 2
8
if k=='u' or k=='U': total 'O' or '0' in the string is: 3
countu+=1 total 'U' or 'u' in the string is: 1
CHECK STRING (PHRASES IN STRINGS):

 Normal:
 With if statement: txt = "The quick brown fox jumps over
 INPUT: the lazy dog!"
 INPUT:
txt = ‘happiness is free“
txt = “happiness is free” if "fox" in txt:
print("free" in txt) print("Yes, 'fox' is present.")
if “free” in txt:
 OUTPUT:
print("Yes, 'free' is present.") else:
True print ("No, ‘fox’ is not present")
 OUTPUT:
 INPUT:
Yes, 'free' is present.
txt = “happiness is free” ## to check for a phrase in a string
print(“hello” in txt)
>>>txt = "The best things in life are free!"
 OUTPUT: >>>print(“life" in txt)
False True 9
CHECK STRING :

 With if statement:
 Normal:
 INPUT:
 INPUT:
txt = “welcome to python“
txt = ‘welcome to python’
if “hello" not in txt:
print(‘world’ not in txt)
print("Yes, ‘hello' is NOT present.")
 OUTPUT:
 OUTPUT:
True
Yes, ‘hello' is NOT present.

10
STRING LENGTH AND SLICING:

 String length:
 String slicing:
 INPUT:
 INPUT:
a = "Hello World”
b = "Hello World“
print(len(a))
print(b[2:5]) ## from index 2 to index4
 OUTPUT:
 OUTPUT:
11
llo
 INPUT:
 INPUT:
a = “Welcome to Python programming @@@“
b = "Hello World“
print (len(a))
print(b[:5]) ## from beginning 5 characters
 OUTPUT:
 OUTPUT:
33 11
Hello
STRING SLICING METHODS:

 With Negative indexing


 From the Start:
 Till the End:  INPUT:
 INPUT:
 INPUT: >>>b = "python is high level
>>>b = ‘’python is high level
programming language“ >>>b = "python is high level programming language“
programming language“ >>>print (b[:-5])
>>>print(b[:10])
>>>print(b[10:]) OUTPUT:
 OUTPUT:
 OUTPUT: python is high level programming lan
python is
high level programming >>>print (b[-5:])
language
OUTPUT:
## consider from the ## skip first 10 characters
beginning 10 characters and from the beginning and print guage 12
print remaining till end of string
STRING SLICING CONTD…

## illustration of slicing
## get a range of characters from the complete string ### Negative indexing

>>>txt = "Govt SKSJTI Bengaluru" >>>txt = "Govt SKSJTI Bengaluru"


# print characters in position 5 to 10. (position 11 not
>>> print(txt[-16:-8]) ## position -8 not
included)
included
>>>print(txt[5:11])
SKSJTI SKSJTI B
## slicing from the beginning without initial index
>>>txt = "Govt SKSJTI Bengaluru"
>>>txt = "Govt SKSJTI Bengaluru" >>> print(txt[:-16])
>>>print(txt[:4]) # from start to position 3 Govt
Govt >>>txt = "Govt SKSJTI Bengaluru"
### slicing till the end without last index >>> print(txt[-9:])
>>>txt = "Govt SKSJTI Bengaluru"
Bengaluru 13
>>>print(txt[7:]) ## from position 7 to last character
SJTI Bengaluru
BUILT-IN STRING METHODS IN PYTHON:

Note: String methods do not modify the original string.  Misc:


 INPUT:
 Upper case:  Lower case:  capitalize:
>>>a = “hello world”
 INPUT:  INPUT:  INPUT: >>> print(a.islower())
>>> a = "Hello World” a = "Hello World“ >>>a = “hello world”  OUTPUT:
>>>print(a.upper()) print(a.lower()) >>> print(a.capitalize()) True
>>>a = “hello world”
 OUTPUT:  OUTPUT:  OUTPUT:
>>> print(a.isupper())
HELLO WORLD hello world Hello world
 OUTPUT:
False
14
BUILT-IN STRING METHODS IN PYTHON

 Splitting string:  INPUT:  Remove Whitespace(strip):

 INPUT: >>>a = " hello,how,are,you”  INPUT:

>>> a = " hello and welcome” >>>print(a.split(‘,’)) >>> a = " Hello World "
>>>print(a.strip())
>>>print(a.split())  OUTPUT:
 OUTPUT:
 OUTPUT: ['hello', 'how', 'are', 'you']
Hello World
['hello', 'and', 'welcome'] ## list with 4 elements
## remove white spaces at the
#list with 3 elements ## splits the string at the specified beginning and end of the string
separator and returns a list. Default
>>>a = " hello,how,are,you” separator white space >>> a = " our first python prog"
>>>print(a.lstrip(‘our’))
>>>print(a.split()) >>>a = “but put cut”
 OUTPUT: OUTPUT:
>>>print(a.split(‘t’))
['hello,how,are,you'] first python prog 15
 OUTPUT:
## list with single element ['bu', ' pu', ' cu', '']
BUILT-IN STRING METHODS IN PYTHON

 Check for alphabets:


 Count occurrence:
 Check for digits:  INPUT:
 INPUT:
 INPUT: a = "Hello 23”
a = "Hello World“
print(a.isalpha())
a = "Hello 23“ print(a.count(‘l’)
 OUTPUT:
print(a.isdigit())  OUTPUT:
False
 OUTPUT: 3
>>>a = “hello "
>>>print(a.isaplpha())  To find position
False (index):
 OUTPUT:
a = “2345’  INPUT:
False
print(a.isdigit()) >>>a = “Hello world”
a = “hello" print(a.isaplpha())
>>> print(a.indix(‘w’))
 OUTPUT:  OUTPUT:
OUTPUT: 16

True False
6
BUILT-IN STRING METHODS IN PYTHON

Replace a character or string:  Concatenation:


INPUT:
 INPUT:
>>>a = “Geeks for Geeks“
print(a.replace(‘G’, ‘W’)) a = "Hello“
OUTPUT: b = "World“
Weeks for Weeks
c=a+b
INPUT: d = a + “, " + b
a = “Hello welcome to Python“
print(a.replace(‘Hello’, ‘Krishna’) print(c)
OUTPUT: print(d)
Krishna welcome to Python
 OUTPUT:
HelloWorld 17

Hello,World
LOOPING TO COUNT:

 INPUT:
 INPUT:
s = "peanut butter“
word='python program’
count = 0
count=0
for char in s:
for letter in word:
if char == "t":
if letter=='p’:
count = count + 1
count=count+1
print(count)
print(count)
 OUTPUT:
 OUTPUT:
3
2 18
PARSING AND FORMAT STRINGS:

 Parsing:
 INPUT:  Format:
st="From mamatha.a@gmail.com"  INPUT:
pos=st.find('@’) print ('My name is %s and age is %d ’ % (‘Arun', 21))
print('Position of @ is', pos)  OUTPUT:
 OUTPUT: My name is Arun and age is 21
Position of @ is 14

19
STRING FORMATTING

 Without built in function:  With built in function:


 INPUT:  INPUT:
age = 36 age = 36
print( "My name is John, I am ", + age) print( "My name is John, I am {} ".format(age))
 OUTPUT:  OUTPUT:
My name is John, I am 36 My name is John, I am 36

20
MULTIPLE PLACE HOLDERS IN STRING FORMAT

 Without index numbers:  With index numbers:

 INPUT:  INPUT:

quantity = 3 quantity = 3
itemno = 5 itemno = 5

price = 49.95 price = 49.95

myorder = “I want {} pieces of item {} for {} myorder = "I want to pay {2} dollars for {0}
dollars.“ pieces of item {1}.“

print(myorder.format(quantity, itemno, price)) print(myorder.format(quantity, itemno, price))

 OUTPUT:  OUTPUT:

I want 3 pieces of item 5 for 49.95 dollars. I want to pay 49.95 dollars for 3 pieces of item 5.21
ESCAPE SEQUENCES

 To insert characters that are illegal in a string, we use an


escape character.
 Example:
 INPUT:
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
 OUTPUT:
We are the so-called "Vikings" from the north.
22
23
STRING COMPARISON:

 Using is operator: >>> id(str1)


 Normal: 1918301558320
 >>>str1=‘python’
>>> id(str2)
 INPUT:
 >>>str2=‘Python’ 1918291321200
>>> print(‘python’==‘python’) >>> id(str3)
 >>>str3=str1 1918301558320
>>> print(’Python’< ‘python’) >>>id(str1)
 >>> str1 is str2
>>> print (’PYTHON’==‘python’) 1918301822256
False is and is not operators check
 OUTPUT: The relational operators compare whether both the operands
>>> str3 is str1
the Unicode values of the characters refer to the same object or
True
of the strings from the zeroth index True not. If object ids are same, it
True till the end of the string. It then returns True
returns a boolean value according to >>> str2 is not str1
False the result of value comparison True 24
.
>>>str1+=‘s’
STRING SPECIAL OPERATORS:

25
SUMMARY OF BUILT-IN STRING METHODS:

Method Description
find() Searches the string for a specified value and
capitalize() Converts the first character returns the position of where it was found
to upper case
format() Formats specified values in a string
casefold() Converts string into lower
case format_map() Formats specified values in a string
center() Returns a centered string index() Searches the string for a specified value and
Returns the number of returns the position of where it was found
count()
times a specified value isalnum() Returns True if all characters in the string are
occurs in a string alphanumeric
encode() Returns an encoded isalpha() Returns True if all characters in the string are
version of the string in the alphabet
endswith() Returns true if the string isdecimal() 26
Returns True if all characters in the string are
ends with the specified decimals
value
CONTD..

isdigit() Returns True if all characters in the string isupper() Returns True if all characters in the
are digits string are upper case
isidentifi Returns True if the string is an identifier join() Joins the elements of an iterable to the end
er() of the string
islower() Returns True if all characters in the string ljust() Returns a left justified version of the string
are lower case
isnumeri Returns True if all characters in the string lower() Converts a string into lower case
c() are numeric
lstrip() Returns a left trim version of the string
isprintab Returns True if all characters in the string
le() are printable maketrans() Returns a translation table to be used in
isspace() Returns True if all characters in the string translations
27
are whitespaces
istitle() Returns True if the string follows the
CONTD..
partition() Returns a tuple where the string is parted
into three parts rsplit() Splits the string at the specified
separator, and returns a list
replace() Returns a string where a specified value is
replaced with a specified value rstrip() Returns a right trim version of the
string
rfind() Searches the string for a specified value
and returns the last position of where it split() Splits the string at the specified
was found separator, and returns a list

rindex() Searches the string for a specified value splitlines() Splits the string at line breaks and
and returns the last position of where it returns a list
was found startswith() Returns true if the string starts with
rjust() Returns a right justified version of the the specified value
string strip() Returns a trimmed version of the
28

rpartition() Returns a tuple where the string is parted string


into three parts

You might also like