About "Not all arguments converted during string formatting" error in Python
Tags: python, programming
Published: 2023-02-04 13:21:07

> ✋ **Update:** This post was originally published on my blog [decodingweb.dev](https://www.decodingweb.dev), where you can read the [latest version](https://www.decodingweb.dev/python-typeerror-not-all-arguments-converted-during-string-formatting-fix) for a 💯 user experience. _~reza_

TypEerror: not all arguments converted during string formatting in Python occurs for the following reasons:

1. **When you’re formatting a string** and number of placeholders and values don’t match
2. **When calculating a division’s remainder** and the lefthand-side operand is a string

Here’s what the error looks like:

```
Traceback (most recent call last):
  File test.py, line 4, in <module>
    print('Hi %s' % (first_name, last_name))
TypeError: not all arguments converted during string formatting
```

## When you're formatting a string

As you probably know, Python supports multiple ways of formatting strings (a.k.a string interpolation):

1. <u>Old string formatting with `%`</u>
2. <u>`str.format()`</u>
3. <u>Formatted string literals (a.k.a f-strings)</u>

### Old string formatting with the %

In the old string formatting (a.k.a printf-style string formatting), we use the `%` (modulo) operator to generate dynamic strings:

```python
string % values
```

The string operand is a string literal containing one or more placeholders identified with `%`. The values operand can be a single value or a tuple of values. These values replace the placeholders in the string (in the order they're defined)

Here's an example:

```python
first_name = 'Tom'
last_name = 'Jones'

print('Hi dear %s' % first_name)
print('Full name: %s %s' % (first_name, last_name))
```

And the output would be:

```
Hi dear Tom
Full name: Tom Jones
```

The s following the `%` is a format specifier, which in this case, specifies the replacement value is of type string. However, if you're inserting a numeric value, you can use `%d` instead.

✋ **Watch out for:** The error "TypeError: not all arguments converted during string formatting" occurs when you want to format a string, but the syntax is invalid - usually when the number of placeholders and values don't match up.

For instance, when you supply more values than the existing placeholders in your format string syntax:

```python
first_name = 'Tom'
last_name = 'Jones'

print('Hi %s' % (first_name, last_name))

# ⛔ Causes TypeError: not all arguments converted during string formatting
```

You'll even get this error if you have supplied values, but there's no placeholder in the string:

```python
first_name = 'Tom'
last_name = 'Jones'

print('Hi' % first_name)

# ⛔ Causes TypeError: not all arguments converted during string formatting
```

So if you're using the old-style string formatting, ensure the number of placeholders and values match.

### Format String Syntax (`str.format()`)

A more robust way of formatting strings is using the `str.format()` method.  

In Format String Syntax, you define a string containing a literal text and a set of replacement fields (surrounded by curly braces). Then, you call `format()` to provide values for those replacement fields.

```python
first_name = 'Tom'
last_name = 'Jones'

print('Hello, {0} {1}').format(first_name, last_name)
# Output: Hello, Tom Jones
```

When passing positional arguments to the `format()` method, you can omit positional argument specifiers, like so:

```python
first_name = 'Tom'
last_name = 'Jones'

print('Hello, {} {}').format(first_name, last_name)
# Output: Hello, Tom Jones
```

Additionally, you can use keyword arguments with the `format()` method:

```python
first_name = 'Tom'
last_name = 'Jones'

print('Hello, {fname} {lname}').format(fname=first_name, lname=last_name)
# Output: Hello, Tom Jones
```

### Formatted string literals

You can also use Formatted string literals (also called f-strings for short) as an alternative to `str.format()`. Formatted string literals let you include the value of Python expressions inside a string. You create an f-string by prefixing it with `f` or `F` and writing expressions inside curly braces.

```python
first_name = 'Tom'
last_name = 'Jones'

print(f'Hello, {first_name} {last_name}')
# Output: Hello, Tom Jones
```

F-strings are what you might want to use for string interpolation.

✋ **Watch out for:** Based on some threads on StackOverflow, some users had mixed up the old formatting syntax with the new string formatter. For instance, they used curly braces in the old string formatting syntax:

```python
first_name = 'Tom'
last_name = 'Jones'

# Raises the error
print('Hello {} {}' % (first_name, last_name))
```

You must use the modulo (`%`) operator when using the prinf-style string formatting.

## When calculating a division's remainder

You might get this type error when using the `%` (modulo) operator to get the remainder of a division if the lefthand operator is a string.

As you probably know, the `%` (modulo) operator is used for two purposes in Python:

1. Old string formatting: `string` `%` `values`
2. Getting a division's remainder: `12 % 2`

When the `%` follows a string, Python considers the expression to be string formatting syntax - rather than an expression calculating a division's remainder.

The following code is supposed to print `"n is Even!"` if the `n` is an even number.

```python
n = '12'

if (n % 2 == 0):
    print('n is Even!')

# ⛔ Causes TypeError: not all arguments converted during string formatting
```

However, it raises TypeError: not all arguments converted during string formatting. The reason is Python's interpreter considered it to be an interpolation syntax.

That said, if you got the number via the `input()` function, you have to cast it to a number first:

Problem solved!

Alright, I think it does it! I hope you found this guide helpful.

Thanks for reading.

---

**❤️ You might like:**

- [TabError: inconsistent use of tabs and spaces in indentation (Python)](https://www.decodingweb.dev/python-taberror-inconsistent-use-of-tabs-and-spaces-in-indentation-fix)
- [How to fix the "TypeError: unhashable type: 'dict'" error in Python](https://www.decodingweb.dev/python-typeerror-unhashable-type-dict-fixed)
- [How to reverse a range in Python (with examples)](https://www.decodingweb.dev/reverse-a-range-in-python)
- [TypeError: missing 1 required positional argument: 'self' (Fixed)](https://www.decodingweb.dev/python-typeerror-missing-1-required-positional-argument-self)
- [Unindent does not match any outer indentation level error in Python (Fixed)](https://www.decodingweb.dev/python-indentationerror-unindent-does-not-match-any-outer-indentation-level-fix)
- [AttributeError module 'DateTime' has no attribute 'strptime' (Fixed)](https://www.decodingweb.dev/attributeerror-module-datetime-has-no-attribute-strptime-python)