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}!")
inputalways returns a string. Convert to numbers withint()orfloat()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 #
- Write code to extract the 2nd and 5th characters from
"Python". - Ask for height and weight with
inputand compute BMI (weight ÷ height²). - Ask for three favourite books or movies and print a summary using
printand f-strings.
参考リンク
Next we’ll consolidate everything into a small program and practice.