~/learn/Python · Fundamentals
Text, indexing and readable output
Build messages, count characters and understand string positions without unexplained jargon.
why this matters
Useful programs communicate results clearly. Text positions and formatted messages also prepare you for cleaning real data.
A string is a sequence of characters: letters, spaces, digits and punctuation. Single or double quotes both work, as long as the opening and closing quotes match. Joining strings with + is called concatenation. A comma in print displays separate values with a space between them.
Try it: Change first_name to Grace. Predict the new length.
len(text) counts characters, including spaces. An index is a position. Python starts counting at 0, so word[0] is the first character. Negative positions count from the end: word[-1] is the last character.
Character positions
word = 'python' character: p y t h o n index: 0 1 2 3 4 5 negative: -6 -5 -4 -3 -2 -1
Try it: Print the last two characters using word[-2:].
A slice selects part of a string. word[start:stop] includes start but stops before stop. Leaving start empty means start at the beginning; leaving stop empty means continue to the end. word[2:5] therefore produces tho.
An f-string is a formatted string. Put f before the opening quote, then place values or calculations inside braces. The formatting instruction :.2f displays a number with two digits after the decimal point; it does not change the stored number.
Try it: Change quantity to 4. The total should display as 10.00.
Text and numbers are different
"Total: " + 3 raises TypeError: Python will not guess how to combine text and a number. Use print("Total:", 3) or f"Total: {3}". Requesting word[99] raises IndexError; a slice past the end is allowed.
Strings cannot be changed in place. This is called immutable. To update text, create a new string and assign it to the name. Later, the Text & files chapter covers cleaning strings with strip, lower, split and join.
key takeaways
- Strings contain characters; len counts them.
- Indexing starts at 0; -1 selects the last character.
- Slices include the start and exclude the stop.
- f-strings insert values into readable text; :.2f displays two decimal places.
check your understanding
word = "python" What is word[1:4]?
free practice
Build confidence with a question you can solve without Pro.