SlideShare a Scribd company logo
1 of 46
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 6
Fundamentals of Programming
Strings
A string is a sequence of characters. You can access the characters
one at a time with the bracket operator
>>> fruit = 'apple'
>>> letter = fruit[1]
The second statement extracts the character at index position 1 from
the fruit variable and assigns it to the letter variable
The expression in brackets is called an index
>>> fruit = 'apple'
>>> letter = fruit[1]
>>> print(letter)
p
in Python, the index is an offset from the beginning of the string, and the offset of the first
letter is zero
>>> fruit = 'apple'
>>> letter = fruit[0]
>>> print(letter)
a
>>> letter = fruit[1.5]
TypeError: string indices must be integers
a p p l e
0 1 2 3 4
Index Number
len
len is a built-in function that returns the number of characters in a
string
>>> fruit = 'apple'
>>>len(fruit)
5
>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range
>>> length = len(fruit)
>>> last = fruit[length-1]
e
Negative Indexing
>>> fruit[-1]
e
a p p l e
-5 -4 -3 -2 -1
Index Number
Traversal through a string with a loop
fruit = 'apple'
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
Traversal through a string with a loop
fruit = 'apple'
for char in fruit:
print(char)
String slices
A segment of a string is called a slice. Selecting a slice is similar
to selecting a character
s = 'Pythonista'
print(s[0:6])
Python
print(s[6:12])
ista
>>> fruit = 'apple'
>>> fruit[:3]
app
>>> fruit[3:]
le
>>> fruit = 'apple'
>>> fruit[3:3]
If the first index is greater than or equal to the second the result
is an empty string
Strings
Strings are immutable
It is tempting to use the operator on the left side of an assignment,
with the intention of changing a character in a string
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print(new_greeting)
Jello, world!
Looping and Counting
The following program counts the number of times the letter "a"
appears in a string
word = 'apple'
count = 0
for letter in word:
if letter == 'p':
count = count + 1
print(count)
The in operator
The word in is a boolean operator that takes two strings and
returns True if the first appears as a substring in the second
>>> 'a' in 'apple'
True
>>> 'seed' in 'apple'
False
String comparison
if word == 'apple':
print('Word Found.')
if word < 'apple':
print('Your word,' + word + ', comes before
apple.')
elif word > 'apple':
print('Your word,' + word + ', comes after
apple.')
else:
print('All right, apples.')
String Methods
Strings are an example of Python objects.
An object contains both data (the actual string itself) and methods,
which are effectively functions that are built into the object and are
available to any instance of the object
Python has a function called dir which lists the methods available for
an object
The type function shows the type of an object and the dir function
shows the available methods
>>> stuff = 'Hello world'
>>> type(stuff)
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count',
'encode', 'endswith' , 'expandtabs', 'find',
'format', 'format_map', 'index' , 'isalnum',
'isalpha', 'isdecimal', 'isdigit', 'isidentifier' ,
'islower', 'isnumeric', 'isprintable', 'isspace' ,
'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip' , 'maketrans', 'partition', 'replace',
'rfind', 'rindex' , 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split' , 'splitlines', 'startswith',
'strip', 'swapcase', 'title' , 'translate', 'upper',
'zfill']
>>> help(str.capitalize)
Help on method_descriptor: capitalize(...)
S.capitalize() -> str Return a capitalized version
of S, i.e. make the first character have upper case
and the rest lower case.
>>>
>>> word = 'apple'
>>> new_word = word.upper()
>>> print(new_word)
APPLE
A method call is called an invocompute scienceion; in this case,
we would say that we are invoking upper on the word
Find
>>> word = 'apple'
>>> index = word.find('a')
>>> print(index)
0
The find method can find substrings as well as characters:
>>> word.find('le')
3
It can take as a second argument the index where it should start:
>>> word.find('p', 2)
2
White Space Removal
One common task is to remove white space (spaces, tabs, or
newlines) from the beginning and end of a string using the strip
method
>>> line = ' Here we go '
>>> line.strip()
Startwiths
>>> line = 'Have a nice day'
>>> line.startswith('Have')
True
>>> line.startswith('h')
False
Lower and Upper
>>> line.lower()
'have a nice day'
>>> line.upper()
'HAVE A NICE DAY'
Parsing Strings
Often, we want to look into a string and find a substring
From adnan@kiu.edu.pk Sat Jan 5 09:14:16 2008
and we wanted to pull out only the second half of the address
(i.e., kiu.edu.pk) from each line
we can do this by using the find method and string slicing
>>> data = 'From adnan@kiu.edu.pk Sat Jan 5 09:14:16 2008'
>>> at_position = data.find('@')
>>> print(at_position)
10
>>> space_position = data.find(' ',at_position)
>>> print(space_position)
21
>>> host = data[at_position+1:space_position]
>>> print(host)
kiu.edu.pk
>>>
First, we will find the position of the at-sign in the string
Then we will find the position of the first space after the at-sign
And then we will use string slicing to extract the portion of the
string which we are looking for
Format Operator
The format operator, % allows us to construct strings, replacing
parts of the strings with the data stored in variables
>>> number = 42
>>> '%d' % number
42
>>> dollars = 42
>>> 'I have spotted %d dollars.' % dollars
'I have spotted 42 dollars.'
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'dollars')
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str
String format()
The format() reads the type of arguments passed to it and
formats it according to the format codes defined in the string
# default arguments
print("Department {}, Field {}.".format("Computer
Science", "GIS"))
# positional arguments
print("Field {1}, Department {0}.".format("Computer
Science", "GIS"))
# keyword arguments
print("Department {depart}, Field
{field}.".format(depart = "Computer Science", field
= "GIS"))
# mixed arguments
print("Department {depart}, Field
{0}.".format("GIS", depart = "Computer Science"))
Number Formatting
Number Formatting Types
Type Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as 'd'. Except it uses current locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as 'g'. Except switches to 'E' if the number is large.
% Percentage. Multiples by 100 and puts % at the end.
# integer arguments
print("Decimal number:{:d}".format(123))
# float arguments
print("Floating point number:{:.2f}".format(123.4567898))
# octal, binary and hexadecimal format
print("Binary: {0:b}, Octal: {0:o}, Hexadecimal:
{0:x}".format(12))
Number Formatting
# integer numbers with minimum width
print("{:5d}".format(12))
# width doesn't work for numbers longer than padding
print("{:2d}".format(1234))
# padding for float numbers
print("{:8.3f}".format(12.2346))
# integer numbers with minimum width filled with
zeros
print("{:05d}".format(12))
# padding for float numbers filled with zeros
print("{:08.3f}".format(12.2346))
Number formatting with alignment
Type Meaning
< Left aligned to the remaining space
^ Center aligned to the remaining space
> Right aligned to the remaining space
= Forces the signed (+) (-) to the leftmost position
# integer numbers with right alignment
print("{:>5d}".format(12))
# float numbers with center alignment
print("{:^10.3f}".format(12.2346))
# integer left alignment filled with zeros
print("{:<05d}".format(12))
# float numbers with center alignment
print("{:=8.3f}".format(-12.2346))

More Related Content

What's hot (19)

Variables In Php 1
Variables In Php 1Variables In Php 1
Variables In Php 1
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Standard data-types-in-py
Standard data-types-in-pyStandard data-types-in-py
Standard data-types-in-py
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
 
Arrays
ArraysArrays
Arrays
 
Python course
Python coursePython course
Python course
 
Python numbers
Python numbersPython numbers
Python numbers
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Basics of Python
Basics of PythonBasics of Python
Basics of Python
 
Pythonintroduction
PythonintroductionPythonintroduction
Pythonintroduction
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 

Similar to Python Lecture 6

Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Input output functions
Input output functionsInput output functions
Input output functionshyderali123
 
Python 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptxPython 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptxTseChris
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfkeerthu0442
 
Python course in_mumbai
Python course in_mumbaiPython course in_mumbai
Python course in_mumbaivibrantuser
 
Unit-IV Strings.pptx
Unit-IV Strings.pptxUnit-IV Strings.pptx
Unit-IV Strings.pptxsamdamfa
 
Sequences: Strings, Lists, and Files
Sequences: Strings, Lists, and FilesSequences: Strings, Lists, and Files
Sequences: Strings, Lists, and FilesEdwin Flórez Gómez
 
The language is C. Thanks. Write a function that computes the intege.pdf
The language is C. Thanks. Write a function that computes the intege.pdfThe language is C. Thanks. Write a function that computes the intege.pdf
The language is C. Thanks. Write a function that computes the intege.pdfforwardcom41
 
Pythonlearn-11-Regex.pptx
Pythonlearn-11-Regex.pptxPythonlearn-11-Regex.pptx
Pythonlearn-11-Regex.pptxDave Tan
 

Similar to Python Lecture 6 (20)

Python String Revisited.pptx
Python String Revisited.pptxPython String Revisited.pptx
Python String Revisited.pptx
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Python
PythonPython
Python
 
Input output functions
Input output functionsInput output functions
Input output functions
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Python programming
Python  programmingPython  programming
Python programming
 
Python 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptxPython 04-ifelse-return-input-strings.pptx
Python 04-ifelse-return-input-strings.pptx
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdf
 
Python
PythonPython
Python
 
PPS_Unit 4.ppt
PPS_Unit 4.pptPPS_Unit 4.ppt
PPS_Unit 4.ppt
 
Python course in_mumbai
Python course in_mumbaiPython course in_mumbai
Python course in_mumbai
 
Unit-IV Strings.pptx
Unit-IV Strings.pptxUnit-IV Strings.pptx
Unit-IV Strings.pptx
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
Sequences: Strings, Lists, and Files
Sequences: Strings, Lists, and FilesSequences: Strings, Lists, and Files
Sequences: Strings, Lists, and Files
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
 
Data Handling
Data Handling Data Handling
Data Handling
 
The language is C. Thanks. Write a function that computes the intege.pdf
The language is C. Thanks. Write a function that computes the intege.pdfThe language is C. Thanks. Write a function that computes the intege.pdf
The language is C. Thanks. Write a function that computes the intege.pdf
 
Pythonlearn-11-Regex.pptx
Pythonlearn-11-Regex.pptxPythonlearn-11-Regex.pptx
Pythonlearn-11-Regex.pptx
 

More from Inzamam Baig

More from Inzamam Baig (13)

Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Lecture 10
Python Lecture 10Python Lecture 10
Python Lecture 10
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
 

Recently uploaded

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Python Lecture 6

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 6 Fundamentals of Programming
  • 2. Strings A string is a sequence of characters. You can access the characters one at a time with the bracket operator >>> fruit = 'apple' >>> letter = fruit[1] The second statement extracts the character at index position 1 from the fruit variable and assigns it to the letter variable The expression in brackets is called an index
  • 3. >>> fruit = 'apple' >>> letter = fruit[1] >>> print(letter) p in Python, the index is an offset from the beginning of the string, and the offset of the first letter is zero >>> fruit = 'apple' >>> letter = fruit[0] >>> print(letter) a
  • 4. >>> letter = fruit[1.5] TypeError: string indices must be integers a p p l e 0 1 2 3 4 Index Number
  • 5. len len is a built-in function that returns the number of characters in a string >>> fruit = 'apple' >>>len(fruit) 5
  • 6. >>> length = len(fruit) >>> last = fruit[length] IndexError: string index out of range
  • 7. >>> length = len(fruit) >>> last = fruit[length-1] e
  • 8. Negative Indexing >>> fruit[-1] e a p p l e -5 -4 -3 -2 -1 Index Number
  • 9. Traversal through a string with a loop fruit = 'apple' index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1
  • 10. Traversal through a string with a loop fruit = 'apple' for char in fruit: print(char)
  • 11. String slices A segment of a string is called a slice. Selecting a slice is similar to selecting a character s = 'Pythonista' print(s[0:6]) Python print(s[6:12]) ista
  • 12. >>> fruit = 'apple' >>> fruit[:3] app >>> fruit[3:] le
  • 13. >>> fruit = 'apple' >>> fruit[3:3] If the first index is greater than or equal to the second the result is an empty string
  • 14. Strings Strings are immutable It is tempting to use the operator on the left side of an assignment, with the intention of changing a character in a string >>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: 'str' object does not support item assignment
  • 15. >>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> print(new_greeting) Jello, world!
  • 16. Looping and Counting The following program counts the number of times the letter "a" appears in a string word = 'apple' count = 0 for letter in word: if letter == 'p': count = count + 1 print(count)
  • 17. The in operator The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second >>> 'a' in 'apple' True >>> 'seed' in 'apple' False
  • 18. String comparison if word == 'apple': print('Word Found.')
  • 19. if word < 'apple': print('Your word,' + word + ', comes before apple.') elif word > 'apple': print('Your word,' + word + ', comes after apple.') else: print('All right, apples.')
  • 20. String Methods Strings are an example of Python objects. An object contains both data (the actual string itself) and methods, which are effectively functions that are built into the object and are available to any instance of the object Python has a function called dir which lists the methods available for an object The type function shows the type of an object and the dir function shows the available methods
  • 21. >>> stuff = 'Hello world' >>> type(stuff)
  • 22. >>> dir(stuff) ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith' , 'expandtabs', 'find', 'format', 'format_map', 'index' , 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier' , 'islower', 'isnumeric', 'isprintable', 'isspace' , 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip' , 'maketrans', 'partition', 'replace', 'rfind', 'rindex' , 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split' , 'splitlines', 'startswith', 'strip', 'swapcase', 'title' , 'translate', 'upper', 'zfill']
  • 23. >>> help(str.capitalize) Help on method_descriptor: capitalize(...) S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. >>>
  • 24. >>> word = 'apple' >>> new_word = word.upper() >>> print(new_word) APPLE
  • 25. A method call is called an invocompute scienceion; in this case, we would say that we are invoking upper on the word
  • 26. Find >>> word = 'apple' >>> index = word.find('a') >>> print(index) 0
  • 27. The find method can find substrings as well as characters: >>> word.find('le') 3 It can take as a second argument the index where it should start: >>> word.find('p', 2) 2
  • 28. White Space Removal One common task is to remove white space (spaces, tabs, or newlines) from the beginning and end of a string using the strip method >>> line = ' Here we go ' >>> line.strip()
  • 29. Startwiths >>> line = 'Have a nice day' >>> line.startswith('Have') True >>> line.startswith('h') False
  • 30. Lower and Upper >>> line.lower() 'have a nice day' >>> line.upper() 'HAVE A NICE DAY'
  • 31. Parsing Strings Often, we want to look into a string and find a substring From adnan@kiu.edu.pk Sat Jan 5 09:14:16 2008 and we wanted to pull out only the second half of the address (i.e., kiu.edu.pk) from each line we can do this by using the find method and string slicing
  • 32. >>> data = 'From adnan@kiu.edu.pk Sat Jan 5 09:14:16 2008' >>> at_position = data.find('@') >>> print(at_position) 10 >>> space_position = data.find(' ',at_position) >>> print(space_position) 21 >>> host = data[at_position+1:space_position] >>> print(host) kiu.edu.pk >>>
  • 33. First, we will find the position of the at-sign in the string Then we will find the position of the first space after the at-sign And then we will use string slicing to extract the portion of the string which we are looking for
  • 34. Format Operator The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in variables >>> number = 42 >>> '%d' % number 42 >>> dollars = 42 >>> 'I have spotted %d dollars.' % dollars 'I have spotted 42 dollars.'
  • 35. >>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'dollars')
  • 36. >>> '%d %d %d' % (1, 2) TypeError: not enough arguments for format string >>> '%d' % 'dollars' TypeError: %d format: a number is required, not str
  • 37. String format() The format() reads the type of arguments passed to it and formats it according to the format codes defined in the string # default arguments print("Department {}, Field {}.".format("Computer Science", "GIS"))
  • 38. # positional arguments print("Field {1}, Department {0}.".format("Computer Science", "GIS"))
  • 39. # keyword arguments print("Department {depart}, Field {field}.".format(depart = "Computer Science", field = "GIS"))
  • 40. # mixed arguments print("Department {depart}, Field {0}.".format("GIS", depart = "Computer Science"))
  • 41. Number Formatting Number Formatting Types Type Meaning d Decimal integer c Corresponding Unicode character b Binary format o Octal format x Hexadecimal format (lower case) X Hexadecimal format (upper case) n Same as 'd'. Except it uses current locale setting for number separator e Exponential notation. (lowercase e) E Exponential notation (uppercase E) f Displays fixed point number (Default: 6) F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN' g General format. Rounds number to p significant digits. (Default precision: 6) G Same as 'g'. Except switches to 'E' if the number is large. % Percentage. Multiples by 100 and puts % at the end.
  • 42. # integer arguments print("Decimal number:{:d}".format(123)) # float arguments print("Floating point number:{:.2f}".format(123.4567898)) # octal, binary and hexadecimal format print("Binary: {0:b}, Octal: {0:o}, Hexadecimal: {0:x}".format(12))
  • 43. Number Formatting # integer numbers with minimum width print("{:5d}".format(12)) # width doesn't work for numbers longer than padding print("{:2d}".format(1234)) # padding for float numbers print("{:8.3f}".format(12.2346))
  • 44. # integer numbers with minimum width filled with zeros print("{:05d}".format(12)) # padding for float numbers filled with zeros print("{:08.3f}".format(12.2346))
  • 45. Number formatting with alignment Type Meaning < Left aligned to the remaining space ^ Center aligned to the remaining space > Right aligned to the remaining space = Forces the signed (+) (-) to the leftmost position
  • 46. # integer numbers with right alignment print("{:>5d}".format(12)) # float numbers with center alignment print("{:^10.3f}".format(12.2346)) # integer left alignment filled with zeros print("{:<05d}".format(12)) # float numbers with center alignment print("{:=8.3f}".format(-12.2346))

Editor's Notes

  1. To get the last letter of a string, you might be tempted to try something like this The reason for the IndexError is that there is no letter in "apple" with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length
  2. Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on
  3. This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string
  4. Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left
  5. An empty string contains no characters and has length 0, but other than that, it is the same as any other string
  6. For now, an object is the same thing as a value, but we will refine that definition late. The reason for the error is that strings are immutable, which means you can't change an existing string
  7. Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters
  8. dir function lists the methods
  9. you can use help to get some simple documentation on a method
  10. This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicompute sciencee that this method takes no argument
  11. In this example, we invoke find on word and pass the letter we are looking for as a parameter
  12. startswith requires case to match
  13. the format sequence %d means that the second operand should be formatted as an integer ("d" stands for "decimal")
  14. If there is more than one format sequence in the string, the second argument has to be a tuple. The following example uses %d to format an integer, %g to format a floating-point number and %s to format a string
  15. The number of elements in the tuple must match the number of format sequences in the string. The types of the elements also must match the format sequences In the first example, there aren't enough elements; in the second, the element is the wrong type