Week 3: Talking to Your Program and Mastering Text
Learn how to get input from users and manipulate strings in Python.
Explore Chapter 3String Manipulation: Working with Text.
Strings are a fundamental data type for representing text. Python provides powerful ways to access and modify strings.
String Indexing
Each character in a string has an index, starting from 0 for the first character. You can access individual characters using square brackets `[]` followed by the index.
text = "Python"
first_char = text[0] # 'P'
second_char = text[1] # 'y'
last_char = text[5] # 'n'
# Negative indexing can be used to access characters from the end of the string
last_char_neg = text[-1] # 'n'
second_last = text[-2] # 'o'
Trying to access an index that is out of range will result in an `IndexError`.
String Slicing
Slicing allows you to extract a substring (a portion of the original string) by specifying a range of indices. The syntax is `[start:end]`, where `start` is the index of the first character to include (inclusive), and `end` is the index of the first character to exclude (exclusive).
text = "Programming"
sub1 = text[0:4] # 'Prog' (from index 0 up to, but not including, index 4)
sub2 = text[4:] # 'ramming' (from index 4 to the end)
sub3 = text[:7] # 'Program' (from the beginning up to, but not including, index 7)
sub4 = text[:] # 'Programming' (a copy of the entire string)
sub5 = text[2:8:2] # 'ormg' (from index 2 to 8, with a step of 2)
sub6 = text[::-1] # 'gnimmargorP' (reversing the string)
String Formatting: Creating Readable Output.
String formatting allows you to embed variables or expressions directly within strings in a clean and readable way. Python offers several ways to do this.
f-strings (Formatted String Literals) - Python 3.6+
f-strings are a concise and readable way to format strings. You create an f-string by prefixing a string literal with the letter `f` or `F`. You can then embed expressions inside curly braces `{}` within the string. These expressions will be evaluated and their values inserted into the string.
name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
price = 19.99
print(f"The price is ${price:.2f}") # Format to 2 decimal places
`.format()` method
The `.format()` method is another way to format strings. You use placeholders `{}` within the string and then call the `.format()` method with the values to be inserted.
name = "Charlie"
city = "New York"
print("My name is {} and I live in {}.".format(name, city))
# You can also use positional or keyword arguments
print("The value at index {0} is {1} and at index {1} is {0}.".format(10, 20))
print("Hello, {name}! Welcome to {place}.".format(name="David", place="London"))