ppt - Multimedia at UCC

Download Report

Transcript ppt - Multimedia at UCC

Programming Training
Main Points:
- Working with strings.
- Problem Solving.
Working with Python String
General facts about strings: str  datatype for Python strings.
A string is a sequence of characters between “”.
input() returns string
Operations on strings
str1 + str2
 new strings which concatenates two strings
str1 * nr
 new string which clones str1 nr times
str1 in str2
 test if str1 is in str2
Indexing / slicing str is a string with n characters
str1[i]
 String formed only with character I
str1[i1:i2]
 Slice of str with all the characters between i1 and i2-1.
str1[i1:]
 Slice with all the characters from i1
Working with Python String
Functions on strings  MUST IMPORT string
len(str1)  the length of str1 or number of characters.
str1 in str2  finds whether str1 is in str2.
str2.count(str1)
 counts how many times str1 occurs in str2.
str1.split(“ch”)
 splits str1 in strings on the ch charter
str1.joint(list)
 makes a new string by
1) joining all list elements
2) separating them using str1
str1.upper() or str1.lower() or str1.dropcase()
 to change the letters case
Working with Python String
Functions on strings  MUST IMPORT string
string.ascii_letters
string.ascii_lowercase
string.ascii_uppercase
string.punctuation
string.digits
are default strings with all mention elements.
Invert a String
Inverting a string requires to form a new string with the letters of the first one in
reverse.
Algorithmic approach:
1. Start from an empty string.
2. Traverse the input string in reverse
1. Append the current letter to the new string
Python approach
rev_str = str1[::-1]
Invert a Sentence
Inverting a sentence requires you to invert the order of words in a sentence but
preserving the words.
Example: “Sabin is teaching the MPT class”  ‘class MPT the teaching is Sabin’
Some questions:
1) how we can acquire the words?  split the string
2) traverse the words in reverse  no problem
3) deal with the ‘.’ if any  just remove it from there e.g. str.remove(‘.’, ‘’)
Steps to solve the problem:
1) input the sentence and remove the ‘.’ if there.
2) split the sentence in words.
3) traverse the word list in reverse and add the current word to the new string.
4) add the ‘.’
Invert a Sentence
Functions to work with:
str2.split()
str2.replace(str1, str2)
str1 + str2
Better Python solution:
' '.join(str1.replace('.', '').split()[::-1])
Try to understand?
Counting Stuff in a String
This requires you to find how many characters are alphabetical, numerical or space.
Is str1 is a single character string then you can test its nature
str1.isalpha()
str1.isdigit()
str1.isspace()etc
It is a simple counting problem in which:
1)
Initialise the counting variables
2)
Traverse the string
1)
Test the nature of the current character and count
To do List
1.
2.
Solve the HW problems.
Read more about Strings