Contents
- 0.1 Strings:
- 0.2 Lists:
- 0.3 1.Strings
- 0.4 Creating a String
- 0.5 Printing a String
- 0.6 String Basics
- 0.7 String Indexing
- 0.8 String Properties
- 0.9 Basic Built-in String methods
- 0.10 Location and Counting
- 0.11 Formatting
- 0.12 is check methods
- 0.13 Built-in Reg. Expressions
- 0.14 2.Lists
- 0.15 Basic List Methods
- 0.16 Nesting Lists
- 1 Advanced Lists
Strings:
Imagine a string as a line of letters, numbers, and symbols. It’s like a sentence or a word in a story, but in the world of computers. Just like you can read and write sentences, a computer can read and write strings. For example:
```python code
# Imagine strings as words or sentences
name = "Alice"
message = "Hello there!"
```
In the above code, we’ve created strings named `name` and `message`. `name` holds the word “Alice,” and `message` holds the sentence “Hello there!”.
Lists:
Think of a list as a collection of items, just like a shopping list or a list of your favorite games. In the computer world, we can use lists to group different things together. Each item in the list can be anything – a number, a word, or even another list. For example:
```python code
# Imagine lists as collections of items
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
```
In the above code, we’ve created lists named `numbers` and `fruits`. `numbers` contains numbers from 1 to 5, while `fruits` contains the words “apple,” “banana,” and “orange.”
**Putting it Together:**
Now, let’s see how we can use strings and lists in some simple ways:
```python code
# Using strings and lists together
greeting = "Hello, " + "world!"
print(greeting)
# Output: Hello, world!
favorite_fruit = fruits[1]
print("My favorite fruit is:", favorite_fruit)
# Output: My favorite fruit is: banana
“`
In the first example, we combined two strings “Hello, ” and “world!” to make the string “Hello, world!” and printed it. In the second example, we used the list `fruits` to get the second item (index 1) which is “banana” and printed a sentence about our favorite fruit.
Remember, strings help us work with text, and lists help us organize different items together. These are basic building blocks, let’s see some more details of strings in jupyter notebook codes with output as shown in the below sections.
Following topics will be covered in strings:
- string creation
- string Printing
- string Indexing
- string properties
- string methods – locating, counting, formatting, is check method.
- built-in expressions: upper(), lower(), split(), count(), find()…etc
Following topics will be covered in Lists:
- List Indexing and slicing
- Lists append.
- List pop
- List Sort
- List reverse
- List Count
- List extend.
- List insert, Remove.
- Nested Lists
1.Strings
Strings are used to record the text information such as name. In Python, Strings act as “Sequence” which means Python tracks every element in the String as a sequence. This is one of the important features of the Python language.
For example, Python understands the string “hello’ to be a sequence of letters in a specific order which means the indexing technique to grab particular letters (like first letter or the last letter).
Creating a String
In Python, either single quote (‘) or double quotes (“) must be used while creating a string.
For example:
# Single word
'hello'
'hello'
# Entire phrase
'This is also a string'
'This is also a string'
# We can also use double quote "String built with double quotes"
'String built with double quotes'
# Be careful with quotes!
' I'm using single quotes, but will create an error'
File "<ipython-input-4-6565b0b7b5e3>", line 2 ' I'm using single quotes, but will create an error' ^ SyntaxError: invalid syntax
The above code results in an error as the text “I’m” stops the string. Here, a combination of single quotes and double quotes can be used to get the complete statement.
"Now I'm ready to use the single quotes inside a string!"
"Now I'm ready to use the single quotes inside a string!"
Now let’s learn about printing strings!
Printing a String
We can automatically display the output strings using Jupyter notebook with just a string in a cell. But,the correct way to display strings in your output is by using a print function.
# We can simply declare a string
'Hello World'
'Hello World'
# note that we can't output multiple strings this way
'Hello World 1'
'Hello World 2'
'Hello World 2'
In Python 2, the output of the below code snippet is displayed using “print” statement as shown in the below syntax but the same syntax will throw error in Python 3.
print 'Hello World 1'
print 'Hello World 2'
print 'Use \n to print a new line'
print '\n'
print 'See what I mean?'
File "<ipython-input-8-30861e38aa5b>", line 1 print 'Hello World 1' ^ SyntaxError: Missing parentheses in call to 'print'
Python 3 Alert!
Note that, In Python 3, print is a function and not a statement. So you would print statements like this:
print(‘Hello World’)
If you want to use this functionality in Python2, you can import form the future module.
Caution: After importing this; you won’t be able to choose the print statement method anymore. So pick the right one whichever you prefer depending on your Python installation and continue on with it.
# To use print function from Python 3 in Python 2
from __future__ import print_function
print('Hello World')
Hello World
String Basics
In Strings, the length of the string can be found out by using a function called len().
len('Hello World')
11
String Indexing
We know strings are a sequence, which means Python can use indexes to call all the sequence parts. Let’s learn how String Indexing works.
• We use brackets [] after an object to call its index.
• We should also note that indexing starts at 0 for Python.
Now, Let’s create a new object called s and the walk through a few examples of indexing.
# Assign s as a string
s = 'Hello World'
#Check
s
'Hello World'
# Print the object
print(s)
Hello World
Let’s start indexing!
# Show first element (in this case a letter)
s[0]
'H'
s[1]
'e'
s[2]
'l'
We can use a : to perform slicing which grabs everything up to a designated point. For example:
# Grab everything past the first term all the way to the length of s which is len(s)
s[1:]
'ello World'
# Note that there is no change to the original s
s
'Hello World'
# Grab everything UP TO the 3rd index
s[:3]
'Hel'
Note the above slicing. Here we’re telling Python to grab everything from 0 up to 3. It doesn’t include the 3rd index. You’ll notice this a lot in Python, where statements and are usually in the context of “up to, but not including”.
#Everything
s[:]
'Hello World'
We can also use negative indexing to go backwards.
# Last letter (one index behind 0 so it loops back around)
s[-1]
'd'
# Grab everything but the last letter
s[:-1]
'Hello Worl'
Index and slice notation is used to grab elements of a sequenec by a specified step size (where in 1 is the default size). For instance we can use two colons in a row and then a number specifying the frequency to grab elements. For example:
# Grab everything, but go in steps size of 1
s[::1]
'Hello World'
# Grab everything, but go in step sizes of 2
s[::2]
'HloWrd'
# We can use this to print a string backwards
s[::-1]
'dlroW olleH'
String Properties
Immutability is one the finest string property which is created once and the elements within it cannot be changed or replaced. For example:
s
'Hello World'
# Let's try to change the first letter to 'x'
s[0] = 'x'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-27-3a9c668aa5ab> in <module>() 1 # Let's try to change the first letter to 'x' ----> 2 s[0] = 'x' TypeError: 'str' object does not support item assignment
Notice how the error tells us directly what we can’t do, change the item assignment!
Something we can do is concatenate strings!
s
'Hello World'
# Concatenate strings!
s + ' concatenate me!'
'Hello World concatenate me!'
# We can reassign s completely though!
s = s + ' concatenate me!'
print(s)
Hello World concatenate me!
s
'Hello World concatenate me!'
We can use the multiplication symbol to create repetition!
letter = 'z'
letter*10
'zzzzzzzzzz'
Basic Built-in String methods
In Python, Objects have built-in methods which means these methods are functions present inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself.
Methods can be called with a period followed by the method name. Methods are in the form:
object.method(parameters)
Where parameters are extra arguments which are passed into the method. Right now, it is not necessary to make 100% sense but going forward we will create our own objects and functions.
Here are some examples of built-in methods in strings:
s
'Hello World concatenate me!'
# Upper Case a string
s.upper()
'HELLO WORLD CONCATENATE ME!'
# Lower case
s.lower()
'hello world concatenate me!'
# Split a string by blank space (this is the default)
s.split()
['Hello', 'World', 'concatenate', 'me!']
# Split by a specific element (doesn't include the element that was split on)
s.split('W')
['Hello ', 'orld concatenate me!']
Print Formatting
Print Formatting “.format()” method is used to add formatted objects to the printed string statements.
Let’s see an example to clearly understand the concept.
'Insert another string with curly brackets: {}'.format('The inserted string')
'Insert another string with curly brackets: The inserted string'
Location and Counting
s.count('o')
3
s.find('o')
4
Formatting
The center() method allows you to place your string ‘centered’ between a provided string with a certain length.
s.center(20,'z')
'Hello World concatenate me!'
expandtabs() will expand tab notations \t into spaces. Let’s see an example to understand the concept.
'hello\thi'.expandtabs()
'hello hi'
is check methods
These various methods below check it the string is some case. Lets explore them:
s = 'hello'
isalnum() will return “True” if all characters in S are alphanumeric.
s.isalnum()
True
isalpha() wil return “True” if all characters in S are alphabetic.
s.isalpha()
True
islower() will return “True” if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
s.islower()
True
isspace() will return “True” if all characters in S are whitespace.
s.isspace()
False
istitle() will return “True” if S is a title cased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.
s.istitle()
False
isupper() will return “True” if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
s.isupper()
False
Another method is endswith() which is essentially same as a boolean check on s[-1]
s.endswith('o')
True
Built-in Reg. Expressions
In Strings, there are some built-in methods which is similar to regular expression operations.
• Split() function is used to split the string at a certain element and return a list of the result.
• Partition is used to return a tuple that includes the separator (the first occurrence), the first half and the end half.
s.split('e')
['h', 'llo']
s.partition('e')
('h', 'e', 'llo')
s
'hello'
2.Lists
Earlier, while discussing introduction to strings we have introduced the concept of a sequence in Python. In Python, Lists can be considered as the most general version of a “sequence”. Unlike strings, they are mutable which means the elements inside a list can be changed!
Lists are constructed with brackets [] and commas separating every element in the list.
Let’s go ahead and see how we can construct lists!
# Assign a list to an variable named my_list
my_list = [1,2,3]
We just created a list of integers, but lists can actually hold different object types. For example:
my_list = ['A string',23,100.232,'o']
Just like strings, the len() function will tell you how many items are in the sequence of the list.
len(my_list)
4
Indexing and Slicing
Indexing and slicing of lists works just like in Strings. Let’s make a new list to remind ourselves of how this works:
my_list = ['one','two','three',4,5]
# Grab element at index 0
my_list[0]
'one'
# Grab index 1 and everything past it
my_list[1:]
['two', 'three', 4, 5]
# Grab everything UP TO index 3
my_list[:3]
['one', 'two', 'three']
We can also use “+” to concatenate lists, just like we did for Strings.
my_list + ['new item',5]
['one', 'two', 'three', 4, 5, 'new item', 5]
Note: This doesn’t actually change the original list!
my_list
['one', 'two', 'three', 4, 5]
In this case, you have to reassign the list to make the permanent change.
# Reassign
my_list = my_list + ['add new item permanently']
my_list
['one', 'two', 'three', 4, 5, 'add new item permanently']
We can also use the * for a duplication method similar to strings:
# Make the list double
my_list * 2
['one', 'two', 'three', 4, 5, 'add new item permanently', 'one', 'two', 'three', 4, 5, 'add new item permanently']
# Again doubling not permanent
my_list
['one', 'two', 'three', 4, 5, 'add new item permanently']
Basic List Methods
If you are familiar with another programming language, start to draw parallels between lists in Python and arrays in other language. There are two reasons which tells why the lists in Python are more flexible than arrays in other programming language:
a. They have no fixed size (which means we need not to specify how big the list will be)
b. They have no fixed type constraint
Let’s go ahead and explore some more special methods for lists:
# Create a new list
l = [1,2,3]
Use the append method to permanently add an item to the end of a list:
# Append
l.append('append me!')
# Show
l
[1, 2, 3, 'append me!']
Use pop to “pop off” an item from the list. By default pop takes off the last index, but you can also specify which index to pop off. Let’s see an example:
# Pop off the 0 indexed item
l.pop(0)
1
# Show
l
[]
# Assign the popped element, remember default popped index is -1
popped_item = l.pop()
popped_item
2
# Show remaining list
l
[2, 3]
Note that lists indexing will return an error if there is no element at that index. For example:
l[100]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-30-e2a0c2623844> in <module> ----> 1 l[100] IndexError: list index out of range
We can use the sort method and the reverse methods to also effect your lists:
new_list = ['a','e','x','b','c']
#Show
new_list
['a', 'e', 'x', 'b', 'c']
# Use reverse to reverse order (this is permanent!)
new_list.reverse()
new_list
['a', 'e', 'x', 'b', 'c']
# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)
new_list.sort()
new_list
['a', 'b', 'c', 'e', 'x']
Nesting Lists
Nesting Lists is one of the great features in Python data structures. Nesting Lists means we can have data structures within data structures.
For example: A list inside a list.
Let’s see how Nesting lists works!
# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]
# Show
matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix[2][1]
8
We can re-use indexing to grab elements, but now there are two levels for the index.
a. The items in the matrix object
b. The items inside the list
# Grab first item in matrix object
matrix[0]
[1, 2, 3]
# Grab first item of the first item in the matrix object
matrix[0][0]
1
In [43]:
# Build a list comprehension by deconstructing a for loop within a []
first_col = [row[0] for row in matrix]
matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
first_col
[1, 4, 7]
Advanced Lists
In this series of lectures, we will be diving a little deeper into all the available methods in a list object. These are just methods that should encountered without some additional exploring. Its pretty likely that you’ve already encountered some of these yourself!
Lets begin!
l = [1,2,3]
append
Definitely, You have used this method by now, which merely appends an element to the end of a list:
l.append(4)
l
[1, 2, 3, 'append me!', 4]
count
We discussed this during the methods lectures, but here it is again. count() takes in an element and returns the number of times it occures in your list:
l.count(10)
0
l.count(2)
1
extend
Many times people find the difference between extend and append to be unclear. So note that,
append: Appends object at end
x = [1, 2, 3]
x.append([4, 5])
print(x)
[1, 2, 3, [4, 5]]
extend: extends list by appending elements from the iterable
x = [1, 2, 3]
x.extend('ty')
print(x)
[1, 2, 3, 't', 'y']
Note how extend append each element in that iterable. That is the key difference.
index
index returns the element placed as an argument. Make a note that if the element is not in the list then it returns an error.
l.index('append me!')
3
l
[1, 2, 3, 'append me!', 4]
l.index(12)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-98-3f090052d656> in <module>() ----> 1 l.index(12) ValueError: 12 is not in list
insert
Two arguments can be placed in insert method.
Syntax: insert(index,object)
This method places the object at the index supplied. For example:
l
[1, 2, 3, 4]
# Place a letter at the index 2
l.insert(100,'inserted')
l[100]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-70-e2a0c2623844> in <module> ----> 1 l[100] IndexError: list index out of range
pop
You most likely have already seen pop(), which allows us to “pop” off the last element of a list.
ele = l.pop(1)
l
[1, 'inserted', 3]
ele
4
remove
The remove() method removes the first occurrence of a value. For example:
l
[1, 2, 'inserted', 3]
l.remove('inserted')
l
[1, 2, 3]
l = [1,2,3,4,3]
l.remove(3)
l
[1, 2, 4, 3]
reverse
As the name suggests, reverse() helps you to reverse a list. Note this occurs in place! Meaning it effects your list permanently.
l.reverse()
l
[3, 4, 2, 1]
sort
sort will sort your list in place:
l
[3, 4, 2, 1]
l.sort()
l
[1, 2, 3, 4]
After completing these codes, go through next lesson: container-objects-functions-python
1 thought on “Python-Strings and list objects”