Welcome to Our Tutorials! Let`s continue.
<What You'll Get Here
We continue with the next lesson.
We study some more python. Ready to dive in? 🚀
Working with strings
Python Tutorial 3: Working with Strings
Program Description
Text is everywhere in programming, and in Python, we handle text using "strings." Strings are sequences of characters, and Python provides many built-in tools to manipulate and work with them. In this tutorial, we'll learn how to create, access, and modify strings.
Illustration
(Imagine an illustration showing letters or words being combined, split, or changed, perhaps with icons representing common string operations like concatenation or slicing.)
Tutorial Sections: Manipulating Text!
Section 1: Creating Strings
Goal: Learn how to define strings in Python.
Explanation: You can create strings by enclosing text in either single quotes (`'...'`) or double quotes (`"..."`). It's generally a good practice to be consistent with which type you use.
Code:
# Creating strings
string1 = "Hello"
string2 = 'World'
string3 = "This is a string with 'single' quotes inside."
string4 = 'This is another string with "double" quotes inside.'
What it means: We've created four different strings, demonstrating the use of both single and double quotes, even when the string contains the other type of quote.
Section 2: String Concatenation (Joining Strings)
Goal: Combine multiple strings into one.
Explanation: You can join strings together using the `+` operator. This is called concatenation.
Code:
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)
What it means: We combined the strings "Hello", ", ", the value of the `name` variable, and "!" to create the message "Hello, Alice!".
Section 3: String Indexing and Slicing
Goal: Access individual characters or parts of a string.
Explanation: Strings are ordered sequences. You can access individual characters using their index (position), starting from 0 for the first character. You can also extract a portion of a string, called a slice, using a colon `:`.
Code:
my_string = "Python"
# Accessing individual characters
first_char = my_string[0] # 'P'
second_char = my_string[1] # 'y'
last_char = my_string[-1] # 'n' (negative index counts from the end)
# Slicing strings
first_three = my_string[0:3] # 'Pyt' (from index 0 up to, but not including, 3)
from_second_on = my_string[1:] # 'ython' (from index 1 to the end)
up_to_fourth = my_string[:4] # 'Pyth' (from the beginning up to, but not including, 4)
print(first_char)
print(last_char)
print(first_three)
What it means: We used square brackets `[]` with indices and slices to get specific characters and substrings from `my_string`.
Excellent! You've taken your first steps in working with text data in Python using strings. Experiment with different strings and try out concatenation and slicing!