For week three we decided to tackle strings, string methods, and functions:
String Methods
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable.
The string data type has multiple methods. Here are all of the methods of list objects:
Examples:
str.upper() – Making Strings uppercase
str.lower() – Making Strings lowercase
str.join() method will concatenate two strings, but in a way that passes one string through another.
str.split() method returns a list of strings that are separated by whitespace if no other parameter is given.
str.replace() method can take an original string and return an updated string with some replacement.
Boolean methods:
Method | True if |
str.isalnum() | If string consists of only alpha-numeric values |
str.isalpha() | If string consists of only alphabets |
str.islower() | If string consists of only lower-case values |
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 |
String comparison
You can use ( > , < , <= , <= , == , != ) to compare two strings. Python compares string lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as “Mary” and str2 as “Mac” . The first two characters fromstr1 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 c ) are compared. And because ‘r’ has greater ASCII value than ‘c’ , str1 is greater than str2 .
Functions:
You use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.
There are three types of functions in Python:
- Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to print an object to the terminal
- User-Defined Functions (UDFs), which are functions that users create to help them out
- Anonymous functions, which are also called lambda functions because they are not declared with the standard def keyword.
Functions vs Methods:
A method refers to a function which is part of a class. You access it with an instance or object of the class. A function doesn’t have this restriction: it just refers to a standalone function. This means that all methods are functions but not all functions are methods.