Week 3: Talking to Your Program and Mastering Text

Learn how to get input from users and manipulate strings in Python.

Explore Chapter 3

The `input()` function for user input.

The `input()` function allows your program to receive data from the user. When `input()` is called, the program pauses and waits for the user to type something into the console and press Enter.

Basic Usage

You can provide an optional string argument to the `input()` function, which will be displayed as a prompt to the user.

name = input("Enter your name: ")
print("Hello,", name + "!")

age_str = input("Enter your age: ")
age = int(age_str) # Convert the input string to an integer
print("You are", age, "years old.")

Important Note: The `input()` function always returns the user's input as a string, even if the user enters a number. You'll often need to convert this string to the appropriate data type (like an integer using `int()`, a float using `float()`, etc.) before you can perform mathematical operations or other type-specific actions.

String 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 Methods: Built-in Tools for Manipulation.

Strings in Python are objects, and they have many useful built-in methods that you can call to perform various operations.

  • `upper()`: Returns a new string with all characters converted to uppercase.
    text = "hello"
    upper_text = text.upper() # "HELLO"
  • `lower()`: Returns a new string with all characters converted to lowercase.
    text = "WORLD"
    lower_text = text.lower() # "world"
  • `strip()`: Returns a new string with leading and trailing whitespace (spaces, tabs, newlines) removed.
    text = "  example string with spaces  \n"
    stripped_text = text.strip() # "example string with spaces"

    You can also use `lstrip()` to remove leading whitespace and `rstrip()` to remove trailing whitespace.

  • `find(substring)`: Returns the index of the first occurrence of the `substring` in the string. If the substring is not found, it returns -1.
    text = "This is a sample text."
    index = text.find("sample") # 10
  • `replace(old, new)`: Returns a new string where all occurrences of the `old` substring are replaced with the `new` substring.
    text = "I like cats."
    new_text = text.replace("cats", "dogs") # "I like dogs."
  • `startswith(prefix)`: Returns `True` if the string starts with the given `prefix`, and `False` otherwise.
  • `endswith(suffix)`: Returns `True` if the string ends with the given `suffix`, and `False` otherwise.
  • `split(separator)`: Splits the string into a list of substrings based on the given `separator`. If no separator is specified, it splits on whitespace.
    text = "apple,banana,cherry"
    fruits = text.split(",") # ['apple', 'banana', 'cherry']
    
    text2 = "words with spaces"
    words = text2.split()    # ['words', 'with', 'spaces']
  • `join(iterable)`: Concatenates the elements of an `iterable` (like a list) into a single string, using the string on which the method is called as the separator.
    words = ["Hello", "Python", "!"]
    sentence = " ".join(words) # "Hello Python !"
  • And many more! (e.g., `count()`, `isdigit()`, `isalpha()`, etc.)

String methods are very powerful and will be used extensively in your Python programming.

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"))
Syllabus