Strings
Objectives
- Understand the nature and importance of strings as a fundamental data type in Python.
- Know how to create, manipulate, and format strings using various techniques.
- Be aware of common string methods and their applications.
- Know how to effectively index, slice, and find the length of strings.
- Understand the concept of string immutability.
- Gain practical experience through programming tasks related to strings.
Earlier we saw how Python works with variables and the data stored in the variable will be of a particular type of data i.e. integers (whole numbers), reals (numbers with a fractional part), characters (e.g. 'a', '5') and boolean (either true or false). In this section we look at strings.
A string is a list of characters, a character being anything that you type on the keyboard in one keystroke e.g. a letter, a number or a symbol, including Space.
Example 3:
Read the following program, and predict what the program will do.
Pay particular attention to the highlighted lines. What will be displayed on the screen when these lines are executed?
Answers
- Full Greeting: Hello Alice
- Shout: HELLO, ALICE
- Whisper: hello, alice
- Length of Full Greeting: 12
- First Letter of Name:
- A Sliced Name: lic
Copy the code and paste into a code editor and run the code to compare your predictions with the actual results.
What are Strings?
- In Python, a string is a data type used to represent text.
- Text can be anything from a single character to a whole paragraph.
- Strings are a fundamental data type in programming and are used extensively in real-world applications.
- A string is a list of characters
Creating Strings
- Strings are created by enclosing text in either single quotes (
'
) or double quotes ("
). - For example:
'Hello, World!'
"Python is fun"
Warning
The type of quotation mark used must be consistent e.g. 'Hello, World!"
is incorrect, the quotes do not match
- to include a quotation mark within a string, use the other one! For example:
String Operations
Two of the operators we saw being used as mathematical operators are repurposed when applied to string operands:
Concatenation
- You can combine two or more strings using the concatenation operator (
+
). -
Example:
-
'Hello' + ' ' + 'World'
results in'Hello World'
.
Repetition
- You can repeat a string multiple times using the repetition operator (
*
). - Example:
'Python' * 3
results in'PythonPythonPython'
.
String Methods
- Python provides many built-in string methods that allow you to manipulate and work with strings effectively.
- Some common string methods include
upper()
,lower()
,len()
,strip()
,split()
, andreplace()
. - Example:
"Python".upper()
results in'PYTHON'
.- When using these do not forget the brackets after the method name, these are function calls and must have the brackets
- To find characters in a string, use the
find()
method. This returns the index of the first occurrence of that character. - For example:
replace()
e.g. course.replace('Python', 'Java')
- To check for the existence of characters in a string, use print('Python' in course)
. This method will returns a boolean value and line find()
is case-sensitive.
String Indexing
- Each character in a string has a unique index starting from
0
. - You can access individual characters in a string using square brackets and the index.
- Example:
"Python"[0]
returns'P'
."Python"[2]
returns't'
.
String Slicing
- String slicing allows you to extract a portion of a string.
- It is done by specifying a range of indices inside square brackets.
- For example:
String Length
- You can find the length of a string using the
len()
function. - Example:
len("Hello, World!")
returns13
.
Escape Characters
- Some characters have special meanings in strings, such as newline (
\n
) and tab (\t
). - To include these characters in a string, you need to use escape sequences.
- Example:
"Hello\nWorld"
creates a string with a newline character.
Multiline Strings
- You can create multiline strings by enclosing them in triple quotes (
'''
or"""
). - Useful for long text or preserving the formatting of text.
- Example:
Printing strings
Python provides three different ways to print the contents of the string to the screen:
Compare the following:
It makes little different which you choose to use but notice the concatenation operator does not insert a space between items being printed.
String Immutability
- Strings in Python are immutable, which means their values cannot be changed after creation.
- Any operation that seems to modify a string actually creates a new string.
- Example:
text = "Hello"
new_text = text + ", World!"
Activity
Modify the given example by:
- Changing the variable values and observe the output.
- Adding more string manipulations using different methods.
- Experimenting with slicing to extract different parts of the string.
Climate Quest Project
Throughout this topic we'll be working on a large scale project: Climate Quest. In this project a player embarks on a journey to combat the effects of climate change by making decisions that impact the environment. Each choice affects the outcome of the game, emphasizing the importance of individual actions in addressing climate change.
Go to task 3 - String Handling
Questions
Programming Tasks
For each of the following tasks write a program using Python.
Write a Python program that asks the user to enter their first name and last name separately. Then, print a formatted message such as 'Hello, [First Name] [Last Name]!', replacing `[First Name]` and `[Last Name]` with the data entered by the user.
Given the string 'Python programming is fun' write a program that converts and displays to screen the string in (a) upper case, (b) lower case and (c) splits the string into individual words
Given the string 'Python programming is fun' use string slicing to extract the following words from the string: (a) 'gram' (b) 'Python' (c) 'program'
Write a Python program that takes a user's input as a sentence and counts the number of words in that sentence. Words are separated by spaces. Print the word count. (For this exercise look up the `split()` method.)