Strings and input/output

Basic python

Strings and input/output

This page covers working with strings and using print / input for basic I/O.

String literals #

Enclose strings in '...' or "...".

greeting = "Hello"
nickname = 'Pythonista'

For multi-line strings, use triple quotes.

message = """You can write
multi-line
messages."""

Working with strings #

"Py" + "thon"        # concatenation => 'Python'
"ha" * 3             # repetition => 'hahaha'
len("💻")             # length => 1

You can access individual characters using indices (starting at 0).

word = "python"
word[0]      # 'p'
word[-1]     # 'n' (last character)

Strings are immutable. Attempting word[0] = "P" raises an error.

Output with print #

print displays multiple values separated by spaces.

name = "Alice"
age = 20
print(name, "is", age, "years old")

Customize the separator or ending with sep and end.

print("A", "B", "C", sep="-")    # A-B-C
print("Hello", end="")           # no newline

Format with f-strings #

From Python 3.6 onward, f-strings provide a readable formatting option.

name = "Alice"
age = 20
print(f"{name} is {age} years old")

You can also specify formats.

pi = 3.1415926535
print(f"{pi:.3f}")   # 3.142

Receive input with input #

input returns the user’s response as a string.

text = input("What's your name? ")
print(f"Welcome, {text}!")

input always returns a string. Convert to numbers with int() or float() when needed.

age_text = input("Enter your age: ")
age = int(age_text)
print(f"You will be {age + 1} next year.")

If conversion fails, Python raises ValueError. You’ll learn error handling later.

Try it yourself #

  1. Write code to extract the 2nd and 5th characters from "Python".
  2. Ask for height and weight with input and compute BMI (weight ÷ height²).
  3. Ask for three favourite books or movies and print a summary using print and f-strings.

Next we’ll consolidate everything into a small program and practice.