Strings
We worked with numeric types (integer, float) in the previous lab. Now we will work with string data type. Just like any data type, a string can be saved in variables. You can think of a string as
a sequence of characters.
Strings are formed by enclosing characters in double quotation or single quotations marks, just make sure to use a matching pair.
You can try the following statements in replit console.
> print("I am a string.")
I am a string.
> type("I am a string.")
<class 'str'>
> print('I am a string too.')
I am a string too.
> type('I am a string too.')
<class 'str'>
> str1 = "Hello"
> str2 = 'Students'
>print(str1,str2)
Hello Students
https://realpython.com/python-data-types/#strings
Accessing elements of a string
# Python Program to access
# characters of a string
>string1 = "Python is fun"
>print(string1)
Python is fun
# Printing the first character of the string
# A string is assiged to a variable name followed by an equal sign and the string in quotation marks.
# Strings in Python are arrays. Arrays are used to store multiple values in one single variable.
# Each array starts at position 0.
print("The first character of the string is: ", string1[0])
P
# Printing Last character
print("\nThe last character of the string is: ", string1[-1])
n
https://www.geeksforgeeks.org/python-data-types/
https://www.w3schools.com/python/python_strings.asp
https://thispointer.com/python-how-to-get-last-n-characters-in-a-string/
The basic string operations are:
String concatenation +
>a = "Hello"
>b = "World"
>a + " " + b
'Hello World'
https://www.w3schools.com/python/python_strings_concatenate.asp
String repetition *
>2 * "Python"
'PythonPython'
https://www.w3schools.in/python-tutorial/repeat-string-in-python/
[] indexing, [:] slicing
To extract a contiguous piece of a string (known as a slice), use a subscript consisting of the starting position
followed by a colon :, finally followed by one more than the ending position of the slice you want to extract.
Notice that the slicing stops before the second value.
For example, consider the string "Hello, World!" and the slice s[0:5].
In this case, the slicing stops before the second value, which means that the slice
will include characters at indices 0, 1, 2, 3, and 4 (corresponding to the letters "H", "e", "l", "l", and "o"),
but it will not include the character at index 5.
>b = "Hello, World!"
>b[2:5]
'llo'
If only : is between [], the whole string is printed.
>b[:]
'Hello, World!'
If the subscript between the brackets is less than zero, python counts from the end of the string,
with a subscript of -1 representing the last character in the string.
> b[-1]
'!'
Detail and more examples are here:
https://www.w3schools.com/python/python_strings_slicing.asp
String methods
Python has many built-in methods (functions) to manipulate strings.
Python strings are immutable, so all these functions return a new string, and the original string remains unchanged.
Here is an example on string upper() method and len() method.
upper() returns a string where all characters are in the upper case.
len() returns the length of the string. len() method can also be used to return the size of a list, dictionary or any other iterable data format.
>a = "Hello, World!"
>a.upper()
HELLO, WORLD!
>len("Hello, World!")
13
Python len() function Examples
Python String split() Method Examples
https://www.w3schools.com/python/python_strings_modify.asp
We cannot combine strings and numbers directly, but we can combine strings and numbers using the format() method.
>m = 5
>o = "oranges"
>s = "I have {} dollars for these {}."
>s.format(m, o)
I have 5 dollars for these oranges.
# {} is used for placing variables m and o. The order of these variables is important.
# Change the order of the variables in s.format() method to see what happens.
https://www.w3schools.com/python/python_strings_format.asp
The find() method finds the first occurrence of the specified value. It returns the position of the value, if not found, returns -1.
>txt = "Python is fun."
>x = txt.find("fun")
>x
10
>x = txt.find("sun")
>x
-1
https://www.w3schools.com/python/ref_string_find.asp
For a list of string methods, here is the link.
https://www.w3schools.com/python/python_strings_methods.asp
Lists
List is a Python data structure. Lists are used to store multiple items in a single variable.
- List items are ordered, changeable, and allow duplicate values.
- Lists are defined by a pair of square [] brackets on either end with individual elements separated by commas.
- List items are indexed. It starts at index [0].
> [1,2]+[3,4]
[1, 2, 3, 4]
> [1,2]*3
[1, 2, 1, 2, 1, 2]
> grades =['A','B','C','D','F']
> grades[0]
'A'
> grades[1:3]
['B', 'C']
> len(grades)
5
#You can mix data types of list items
> a = [3,'cats', 6.17, 2+0j]
> a[1]
'cats'
> a[3]
(2+0j)
#You can change individual elements
a =[3,'cats', 6.17, 2+0j]
> a
[3, 'cats', 6.17, (2+0j)]
> a[0] = a[0] + 4
> a
[7, 'cats', 6.17, (2+0j)]
#You can also manipulate individual string elements
> a[1] = a[1] +' and dogs'
> a
[7, 'cats and dogs', 6.17, (2+0j)]
More examples on access, append, remove, change, slicing lists, detailed lists methods are listed below.
> a = [1,2,3]
> a
[1, 2, 3]
> a.append(4)
> a
[1, 2, 3, 4]
> a.append('hello')
> a
[1, 2, 3, 4, 'hello']
> a.pop()
'hello'
> a
[1, 2, 3, 4]
> a.append("again")
> a
[1, 2, 3, 4, 'again']
> a.remove(4)
> a
[1, 2, 3, 'again']
> a.remove('again')
> a
[1, 2, 3]
> a.append(4)
> a
[1, 2, 3, 4]
> a.append('hello')
> a
[1, 2, 3, 4, 'hello']
> a.pop()
'hello'
> a
[1, 2, 3, 4]
> a.append("again")
> a
[1, 2, 3, 4, 'again']
> a[-1]
'again'
> a[1]
2
> a[1:5]
[2, 3, 4, 'again']
> a[:5]
[1, 2, 3, 4, 'again']
> a[:1]
[1]
> a[:3]
[1, 2, 3]
> a.clear()
> a
[]
Manipulating Lists
You can access list items, change list items, add or remove list items, loop list items, sort, copy, and join list items.
Please see the following link.
https://www.w3schools.com/python/python_lists.asp
Slicing Lists
You can access pieces of lists using the slicing feature of Python:
https://railsware.com/blog/python-for-machine-learning-indexing-and-slicing-for-lists-tuples-strings-and-other-sequential-types/
Lists Methods
Python has a set of built-in methods that you can use on lists.
https://www.w3schools.com/python/python_lists_methods.asp
The differences between Strings and Lists
Lists are mutable (changeable). Strings are immutable.
> mylist = [5,9,12,45]
> mylist[2]
12
> mylist[2] = 0
> mylist
[5, 9, 0, 45]
> mystring = "This is a string."
> mystring[2]
'i'
> mystring[2] = 'p'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
Tuples
Tuples are lists that are immutable. The individual elements of a tuple cannot be changed.
List is written in square brackets. A tuple is written in round brackets.
>a_tuple = ("apple", "pear", "orange")
>a_tuple
('apple','pear','orange')
https://www.w3schools.com/python/python_tuples.asp
To access tuple elements, you can use index number, inside square brackets.
https://www.w3schools.com/python/python_tuples_access.asp
Since tuples are unchangeable/immutable, you can convert the tuple into a list, change the list, and convert the list back into a tuple.
https://www.w3schools.com/python/python_tuples_update.asp
You can loop through tuple elements by using a for loop.
https://www.w3schools.com/python/python_tuples_loop.asp
To join two or more tuples you can use the + operator:
https://www.w3schools.com/python/python_tuples_join.asp
Python has two built-in methods that you can use on tuples.
https://www.w3schools.com/python/python_tuples_methods.asp
For a set of Python programs you can try with tuples, check out the following examples.
https://www.w3resource.com/python-exercises/tuple/
The differences between Lists and Tuples
Lists use [] and Tuples use ().
More detailed diffferences between Lists and Tuples are below.
https://www.geeksforgeeks.org/python-difference-between-list-and-tuple/
Lab Assignment
1. Write a program words.py to count the number of words in a sentence.
Steps include:
- Ask a user to enter a string and save the input string into a variable.
- Use split() and len() methods to count words in a string and save the result in a variable.
Note: there are many ways to write this program. You can use split() and len() methods or any other technique to solve this problem.
- Print the number of words in a sentence.
Sample outputs of the program.
This program counts the number of words in a sentence.
Enter a string: Python is an interpreted and high-level programming language.
Number of words: 8
--------------------------------------------------------------------------------
This program counts the number of words in a sentence.
Enter a string: The dog jumped over the cat.
Number of words : 6
2. Write a program username.py to generate a username based on the user's first name and last name.
Steps include:
- Ask the user to enter first name and last name as input.
- Extract the first character of the first name (make it capital), concatenates up to 7 characters of the last name.
- Make use of .upper() method
- Output the generated username.
Sample outputs of the program.
This program generates computer usernames.
Please enter your first name (all lowercase): catherine
Please enter your last name (all lowercase): song
Your username is: Csong
----------------------------------------------------
This program generates computer usernames.
Please enter your first name (all lowercase): john
Please enter your last name (all lowercase): smith
Your username is: Jsmith
----------------------------------------------------
Demonstrate your completed programs to your lab instructor if the lab is in person.