Strings 3 - methods
Download exercises zip
Every data type has associated particular methods for that type, let’s see the simple ones associated to type string (str
):
Method |
Result |
Meaning |
---|---|---|
|
Return the string with all characters uppercase |
|
|
Return the string with all characters lowercase |
|
|
Return the string with the first uppercase character |
|
|
Check if the string begins with another one |
|
|
Check whether the string ends with another one |
|
|
Check if all characters are alhpabetic |
|
|
Check if all characters are digits |
|
|
Check if all characters are uppercase |
|
|
Check if all characters are lowercase |
The others are described at the page Search methods
WARNING: ALL string methods ALWAYS generate a NEW string
The original string object is NEVER changed (strings are immutable).
What to do
Unzip exercises zip in a folder, you should obtain something like this:
strings
strings1.ipynb
strings1-sol.ipynb
strings2.ipynb
strings2-sol.ipynb
strings3.ipynb
strings3-sol.ipynb
strings4.ipynb
strings4-sol.ipynb
strings5-chal.ipynb
jupman.py
WARNING: to correctly visualize the notebook, it MUST be in an unzipped folder !
open Jupyter Notebook from that folder. Two things should open, first a console and then browser. The browser should show a file list: navigate the list and open the notebook
strings3.ipynb
Go on reading the exercises file, sometimes you will find paragraphs marked Exercises which will ask to write Python commands in the following cells.
Shortcut keys:
to execute Python code inside a Jupyter cell, press
Control + Enter
to execute Python code inside a Jupyter cell AND select next cell, press
Shift + Enter
to execute Python code inside a Jupyter cell AND a create a new cell aftwerwards, press
Alt + Enter
If the notebooks look stuck, try to select
Kernel -> Restart
Example - upper
A method is a function of an object that takes as input the object to which is it is applied and performs some calculation.
The string type str
has predefined methods like str.upper()
which can be applied to other string objects (i.e.: 'hello'
is a string object)
The method str.upper()
takes the string to which it is applied, and creates a NEW string in which all the characters are in uppercase. To apply a method like str.upper()
to the particular string object 'hello'
, we must write:
'hello'.upper()
Frst we write the object on which apply the method ('hello'
), then a dot .
, and afterwards the method name followed by round parenthesis. The brackets can also contain further parameters according to the method.
Examples:
[2]:
'hello'.upper()
[2]:
'HELLO'
[3]:
"I'm important".upper()
[3]:
"I'M IMPORTANT"
WARNING: like ALL string methods, the original string object on which the method is called does NOT get modified.
Example:
[4]:
x = "hello"
y = x.upper() # generates a NEW string and associates it to the variables y
[5]:
x # x variable is still associated to the old string
[5]:
'hello'
[6]:
y # y variable is associated to the new string
[6]:
'HELLO'
Have a look now at the same example in Python Tutor:
[7]:
x = "hello"
y = x.upper()
print(x)
print(y)
jupman.pytut()
hello
HELLO
[7]:
Exercise - walking
Write some code which given a string x
(i.e.: x='walking'
) prints twice the row:
walking WALKING walking WALKING
walking WALKING walking WALKING
DO NOT create new variables
your code must work with any string
[8]:
x = 'walking'
print(x, x.upper(), x, x.upper())
print(x, x.upper(), x, x.upper())
walking WALKING walking WALKING
walking WALKING walking WALKING
Help: If you are not sure about a method (for example, strip
), you can ask Python for help this way:
WARNING: when using help, DON’T put parenthesis after the method name !!
[9]:
help("hello".strip)
Help on built-in function strip:
strip(chars=None, /) method of builtins.str instance
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
lower
method
Return the string with all lowercase characters
[10]:
my_string = "HEllo WorLd"
another_string = my_string.lower()
print(another_string)
hello world
[11]:
print(my_string) # didn't change
HEllo WorLd
Exercise - lowermid
Write some code that given any string x
of odd length, prints a new string like x
having the mid-character as lowercase.
your code must work with any string !
HINT: to calculate the position of the mid-character, use integer division with the operator
//
Example 1 - given:
x = 'ADORATION'
it should print:
ADORaTION
Example 2 - given:
x = 'LEADINg'
it should print:
LEAdINg
[12]:
#012345678
x = 'ADORATION'
#x = 'LEADINg'
# write here
capitalize
method
capitalize()
creates a NEW string having only the FIRST character as uppercase:
[13]:
"artisan".capitalize()
[13]:
'Artisan'
[14]:
"premium".capitalize()
[14]:
'Premium'
[15]:
x = 'goat'
y = 'goat'.capitalize()
[16]:
x # x remains associate to the old value
[16]:
'goat'
[17]:
y # y is associated to the new string
[17]:
'Goat'
Exercise - Your Excellence
Write some code which given two strings x
and y
returns the two strings concatenated, separating them with a space and both as lowercase except the first two characters which must be uppercase
Example 1 - given:
x = 'yoUR'
y = 'exCelLenCE'
it must print:
Your Excellence
Example 2 - given:
x = 'hEr'
y = 'maJEsty'
it must print:
Her Majesty
[18]:
x,y = 'yoUR','exCelLenCE'
#x,y = 'hEr','maJEsty'
# write here
startswith
method
str.startswith
takes as parameter a string and returns True
if the string before the dot begins with the string passed as parameter. Example:
[19]:
"the dog is barking in the road".startswith('the dog')
[19]:
True
[20]:
"the dog is barking in the road".startswith('is barking')
[20]:
False
[21]:
"the dog is barking in the road".startswith('THE DOG') # uppercase is different from lowercase
[21]:
False
[22]:
"THE DOG BARKS IN THE ROAD".startswith('THE DOG') # uppercase is different from lowercase
[22]:
True
Exercise - by Jove
Write some code which given any three strings x
, y
and z
, prints True
if both x
and y
start with string z
, otherwise prints False
Example 1 - given:
x = 'by Jove'
y = 'by Zeus'
z = 'by'
it should print:
True
Example 2 - given:
x = 'by Jove'
y = 'by Zeus'
z = 'from'
it should print:
False
Example 3 - given:
x = 'from Jove'
y = 'by Zeus'
z = 'by'
it should print:
False
[23]:
x,y,z = 'by Jove','by Zeus','by' # True
#x,y,z = 'by Jove','by Zeus','from' # False
#x,y,z = 'from Jove','by Zeus','by' # False
# write here
endswith
method
str.endswith
takes as parameter a string and returns True
if the string before the dot ends with the string passed as parameter. Example:
[24]:
"My best wishes".endswith('st wishes')
[24]:
True
[25]:
"My best wishes".endswith('best')
[25]:
False
[26]:
"My best wishes".endswith('WISHES') # uppercase is different from lowercase
[26]:
False
[27]:
"MY BEST WISHES".endswith('WISHES') # uppercase is different from lowercase
[27]:
True
Exercise - Snobbonis
Given couple names husband
and wife
, write some code which prints True
if they share the surname, False
otherwise.
assume the surname is always at position
9
your code must work for any couple
husband
andwife
[28]:
#0123456789 #0123456789
husband, wife = 'Antonio Snobbonis', 'Carolina Snobbonis' # True
#husband, wife = 'Camillo De Spaparanzi', 'Matilda Degli Agi' # False
# write here
isalpha
method
The method isalpha
returns True
if all characters in the string are alphabetic:
[29]:
'CoralReel'.isalpha()
[29]:
True
Numbers are not considered alphabetic:
[30]:
'Route 666'.isalpha()
[30]:
False
Also, blanks are not alphabetic:
[31]:
'Coral Reel'.isalpha()
[31]:
False
… nor punctuation:
[32]:
'!'.isalpha()
[32]:
False
… nor weird Unicode stuff:
[33]:
'♥'.isalpha()
[33]:
False
[34]:
''.isalpha()
[34]:
False
Exercise - Fighting the hackers
In the lower floors of Interpol, it is well known international hackers communicate using a slang called Leet. This fashion is also spreading in schools, where you are considered K001 (cool) if you know this inconvenient language. The idea is trying to substitute characters with numbers in written text ( Complete guide ).
1 -> i
2 -> z
3 -> e
4 -> h, a, y
etc
Write some code which checks name
and surname
given by students to detect Leet-like language.
print
True
if at least one of the words contains numbers instead of alphabet characters, otherwise printFalse
code must be generic, so must work with any word
DO NOT use
if
command
[35]:
name, surname = 'K001', 'H4ck3r' # True
#name, surname = 'Cool', 'H4ck3r' # True
#name, surname = 'Romina', 'Rossi' # False
#name, surname = 'Peppo', 'Sbirilli' # False
#name, surname = 'K001', 'Sbirilli' # True
# write here
isdigit
method
isdigit
method returns True
if a string is only composed of digits:
[36]:
'391'.isdigit()
[36]:
True
[37]:
'400m'.isdigit()
[37]:
False
Floating point and scientific notations are not recognized:
[38]:
'3.14'.isdigit()
[38]:
False
[39]:
'4e29'.isdigit()
[39]:
False
Exercise - Selling numbers
The multinational ToxiCorp managed to acquire a wealth of private data of unaware users, and asks you to analyze it. They will then sell private information to the highest bidder on the black market. The offer looks questionable, but they pay well, so you accept.
We need to understand the data and how to organize it. You found several strings which look like phone numbers.
Every number should be composed like so:
+[national prefix 39][10 numbers]
For example, this is a valid number: +392574856985
Write some code which prints True
if the string is a phone number, False
otherwise
Try the various combinations by uncommenting
phone =
Your code must be generic, should be valid for all numbers
[40]:
phone = '+392574856985' # True
#phone = '395851256954' # False (missing '+')
#phone = '++7485125874' # False (missing prefix)
#phone = '+3933342Blah' # False (obvious :D )
#phone = "+3912" # False (too short)
#phone = '+393481489942' # True
# write here
isupper
and islower
methods
We can check whether a character is uppercase or lowercase with isupper
and islower
methods:
[41]:
'q'.isupper()
[41]:
False
[42]:
'Q'.isupper()
[42]:
True
[43]:
'b'.islower()
[43]:
True
[44]:
'B'.islower()
[44]:
False
They also work on longer strings, checking if all characters meet the criteria:
[45]:
'GREAT'.isupper()
[45]:
True
[46]:
'NotSoGREAT'.isupper()
[46]:
False
Note blanks and punctuation are not taken into account:
[47]:
'REALLY\nGREAT !'.isupper()
[47]:
True
We could check whether a character is upper/lower case by examining its ASCII code but the best way to cover all alphabets is by using isupper
and islower
methods. For example, they also work with accented letters:
[48]:
'à'.isupper()
[48]:
False
[49]:
'Á'.isupper()
[49]:
True
Exercise - dwarves and GIANTS
In an unknown and exciting fantasy world live two populations, dwarves and GIANTS:
dwarves love giving their offspring names containing only lowercase characters
GIANTS don’t even need to think about it, because it’s written on the tablets of GROCK that GIANT names can only have uppercase characters
One day, a threat came from a far away kingdom, and so a team of fearless adventurers was gathered. The prophecy said only a mixed team of GIANTS and dwarves for a total of 4 people could defeat the evil.
Write some code which checks whether or not four adventurers can gather into a valid team:
print
True
if the four names are both of dwarves and GIANTS, otherwise if they are of only one of the populations printFalse
your code must be generic, valid for all strings
Find some GIANT names and dwarves names and try to put them, making sure to translate them with the all uppercase / all lowercase capitalization, es “Jisog” is not a valid giant name, it must be translated into the gigantic writing “JISOG”
[50]:
adv1, adv2, adv3, adv4 = 'gimli', 'savorlim', 'glazouc', 'hondouni' # False
#adv1, adv2, adv3, adv4 = 'OXLOR', 'HIVAR', 'ELOR', 'SUXGROG' # False
#adv1, adv2, adv3, adv4 = 'krakrerlig', 'GUCAM', 'SUXGROG', 'kodearen' # True
#adv1, adv2, adv3, adv4 = 'yarnithra', 'krakrerlig', 'jandreda', 'TOVIR' # True
# write here
Continue
Go on reading notebook Strings 4 - search methods
[ ]: