The same symbol does different things depending on what you give it. + adds two numbers, joins two strings, and merges two lists. * multiplies numbers but repeats text. % gives a remainder with numbers and formats text with strings. This is not Python being inconsistent. Each type decides what its own operators mean, and once you see that as a rule instead of a list of surprises, a whole class of confusing bugs disappears.
The previous lesson in this module covered "Arithmetic Operators and Operator Precedence", and the next lesson in this module is about "Type Conversion (Casting) Without Bugs".
Why does the same symbol do different things?
Every operator is really a request to call a method on the objects involved. When you write a + b, Python looks for __add__ on the left object and calls it with the right one. Integers make __add__ add. Strings make it join. Lists make it merge. Because the rule lives with the type, each type decides for itself, and a type that does not support an operation simply does not define the method at all.
print('int + int ->', 2 + 3)
print('str + str ->', 'ab' + 'cd')
print('list + list ->', [1, 2] + [3])
print('int * int ->', 2 * 3)
print('str * int ->', 'ab' * 3)
print('list * int ->', [0] * 3)
try:
print('ab' - 'cd')
except TypeError as error:
print('str - str ->', error)
The subtraction case shows the mechanism clearly. str does not define __sub__, so Python raises TypeError and tells you exactly which operation and which types were involved. Read that message as "strings do not support subtraction", and not as a puzzle that you need to solve.
| Operation | On numbers | On strings |
|---|---|---|
+ | arithmetic addition | joins into a new string |
* | multiplication | repetition, and the count must be a whole number |
% | remainder after floor division | old-style formatting |
< | numeric order | character-by-character order |
What happens when you mix a string and a number?
You get a TypeError, and the message is unusually helpful because it prints both of the types.
try:
print('5' + 5)
except TypeError as error:
print('mixed + failed ->', error)
print('but "5" * 5 works ->', '5' * 5)
try:
print(sum(['1', '2', '3']))
except TypeError as error:
print('sum of strings failed ->', error)
values = ['1', '2', '3']
numbers = []
for value in values:
numbers.append(int(value))
print('converted total ->', sum(numbers))
The '5' * 5 line causes the most confusion, because it works. Multiplication on a string means "repeat", and repeating needs a count, so '5' * 5 is '55555'. The rule is not that strings and numbers mix. The rule is that each operator means something different on each type, and only some of those combinations make sense.
The useful habit is to convert at the boundary. Data arrives as text, so convert it once, at the place where it enters your program, and work with real numbers everywhere else. The last four lines of the example do exactly that. They convert each item and then give the numbers to sum().
One detail matters when the text is not a clean number. int() refuses anything with a decimal point in it, so '3.5' raises ValueError instead of quietly becoming 3. That refusal is a good thing, because it stops a decimal value from being stored as a whole number and losing its decimal part along the way.
How does the % operator work on strings?
On a string, % is printf-style formatting. It comes from C, and it is much older than f-strings. You write the placeholders inside the string and give the values after it. With more than one placeholder, the values must be passed as a tuple.
name = 'Ada'
count = 3
share = 25.6
print('%s owns %d files (%.1f%%)' % (name, count, share))
print('one value ->', '%s is ready' % name)
print('escaped percent ->', 'progress: 50%%' % ())
Two traps live here. The first one is that %d insists on a real number, so a string that looks numeric still fails. The second one is the percent sign itself. % starts a placeholder, so writing 50% inside a formatted string breaks, and %% is how you print one percent sign.
You will still meet this style in older codebases and in logging libraries, so it is worth recognising. For new code, use f-strings. They are faster, they do not need a tuple, and the expression sits right next to the text that it produces.
One difference between the two styles catches people out. In printf-style formatting, the conversion code decides how a value is shown. %s is for text, %d is for a whole number, %f is for a decimal, and %.2f is for a decimal with two places. The type check happens at that moment, so a value that arrives as text but should be a number fails loudly. That is useful when your data is messy, and it is one reason the style lasted so long in logging code.
How do comparisons behave for text?
Comparing two strings does not compare them as numbers, and it does not compare them as an alphabet either. It compares them character by character, using the Unicode code point of each character. So capital letters come before small letters, and digits come before letters.
print('"apple" < "banana" ->', 'apple' < 'banana')
print('"Zebra" < "apple" ->', 'Zebra' < 'apple')
print('"10" < "9" ->', '10' < '9')
print('10 < 9 ->', 10 < 9)
names = ['apple', 'Banana', 'apricot', 'Cherry']
print('plain sort ->', sorted(names))
print('casefold sort ->', sorted(names, key=str.casefold))
Two results matter in real work. Sorting text that contains numbers gives you '10' before '9', because you are comparing characters and not amounts. And sorting mixed-case text puts every capitalised word before every small-letter word, which looks wrong to a reader. Passing key=str.casefold fixes that, because it compares a normalised copy of each string instead of the original.
Your turn: build a safe text-to-number adder
- Write a function
add_values(raw_a, raw_b)that takes two strings, converts both withint()orfloat(), and returns their sum. Decide up front whether it handles decimals, and say so in the docstring. - Run it with
'42'and'8'. It must print 50 and never raise an error. - Now call it with
'42'and'eight'. CatchValueErrorand print a message that names which argument failed. Use the variable names and not the raw values, so that a password never ends up in your logs. - Add a variant that handles values with units, such as
'12kg', by removing the unit before you convert. Write down what you accept and what you reject. - Finish with the safe version of the accidental success that you met earlier. Write one function that takes a digit string and a count and returns the digit repeated, and another one that raises a clear error when the count is not a non-negative whole number.
Rules of thumb
- Every operator asks the types what the operation means, so one symbol can have several meanings.
+adds numbers, joins strings, and merges lists, while*multiplies numbers and repeats strings.- A
TypeErrormessage names both of the types. Read it as a statement about which operation that pair of types does not support. - Convert text to numbers once, at the boundary, instead of spreading conversions through your logic.
- Text comparison is character by character, so sort numbers as numbers and use
key=str.casefoldfor name lists that people will read.