Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

84%
+9 −0
Q&A Why don't format specifiers work with lists, dictionaries and other objects?

When I want to print a number or a string, I can use f-strings (Python >= 3.6) or str.format, and I can use just the variable between braces, or use format specifiers. Ex: num, text = 10, 'abc' ...

1 answer  ·  posted 3y ago by hkotsubo‭  ·  edited 3y ago by sth‭

#2: Post edited by user avatar sth‭ · 2020-08-25T12:51:04Z (over 3 years ago)
  • When I want to print a number or a string, I can use [*f-strings*](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) (Python >= 3.6) ou [`str.format`][1], and I can use just the variable between braces, or use [format specifiers](https://docs.python.org/3/library/string.html#formatspec). Ex:
  • ```python
  • num, text = 10, 'abc'
  • # passing just the variables
  • print(f'{num} {text}')
  • # or
  • #print('{} {}'.format(num, text))
  • # using format specifiers
  • # number left-aligned, with 6 spaces, text right-aligned with 10 spaces
  • print(f'{num:<6} {text:>10}')
  • # or
  • #print('{:<6} {:>12}'.format(num, text))
  • ```
  • Output:
  • ```none
  • 10 abc
  • 10 abc
  • ```
  • But if I do the same with lists or dictionaries, only the first option works:
  • ```python
  • mylist = [1, 2]
  • dic = {'a': 1}
  • # this works
  • print(f'{mylist} {dic}')
  • # or
  • #print('{} {}'.format(mylist, dic))
  • # this doesn't work
  • print(f'{mylist:<10} {dic:>15}')
  • # or
  • #print('{:<10} {:>15}'.format(mylist, dic))
  • ```
  • The first `print` outputs:
  • ```none
  • [1, 2] {'a': 1}
  • ```
  • But the second `print` (with the format specifiers `<10` and `>15`) gives this error:
  • > TypeError: unsupported format string passed to list.__format__
  • ---
  • If I try the same thing with an instance of a class that I created, the same thing occurs. Ex:
  • ```python
  • class Test:
  • def __init__(self, value):
  • self.value = value
  • def __str__(self):
  • return f'Test({self.value})'
  • t = Test(42)
  • print(f't={t}') # this works
  • print(f'{t:>10}') # this doesn't work
  • ```
  • The first `print` outputs:
  • ```none
  • t=Test(42)
  • ```
  • The second `print` gives an error:
  • > TypeError: unsupported format string passed to Test.__format__
  • ---
  • My question is **not** about how to fix it (*I could just convert the list/dictionary/object to string, either by using [`str`](https://docs.python.org/3/library/functions.html#func-str), or by iterating through its elements or atributes and manually building the string, etc*).
  • What I want to know is **why this happens**. Why it's not possible to use format specifiers with lists, dictionaries and instances of my own classes, but if I pass them without any specifiers, it works? Are there any internal details about those types, that make them behave differently to numbers and strings, when those are formatted?
  • [1]: https://docs.python.org/3/library/stdtypes.html#str.format
  • When I want to print a number or a string, I can use [*f-strings*](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) (Python >= 3.6) or [`str.format`][1], and I can use just the variable between braces, or use [format specifiers](https://docs.python.org/3/library/string.html#formatspec). Ex:
  • ```python
  • num, text = 10, 'abc'
  • # passing just the variables
  • print(f'{num} {text}')
  • # or
  • #print('{} {}'.format(num, text))
  • # using format specifiers
  • # number left-aligned, with 6 spaces, text right-aligned with 10 spaces
  • print(f'{num:<6} {text:>10}')
  • # or
  • #print('{:<6} {:>12}'.format(num, text))
  • ```
  • Output:
  • ```none
  • 10 abc
  • 10 abc
  • ```
  • But if I do the same with lists or dictionaries, only the first option works:
  • ```python
  • mylist = [1, 2]
  • dic = {'a': 1}
  • # this works
  • print(f'{mylist} {dic}')
  • # or
  • #print('{} {}'.format(mylist, dic))
  • # this doesn't work
  • print(f'{mylist:<10} {dic:>15}')
  • # or
  • #print('{:<10} {:>15}'.format(mylist, dic))
  • ```
  • The first `print` outputs:
  • ```none
  • [1, 2] {'a': 1}
  • ```
  • But the second `print` (with the format specifiers `<10` and `>15`) gives this error:
  • > TypeError: unsupported format string passed to list.__format__
  • ---
  • If I try the same thing with an instance of a class that I created, the same thing occurs. Ex:
  • ```python
  • class Test:
  • def __init__(self, value):
  • self.value = value
  • def __str__(self):
  • return f'Test({self.value})'
  • t = Test(42)
  • print(f't={t}') # this works
  • print(f'{t:>10}') # this doesn't work
  • ```
  • The first `print` outputs:
  • ```none
  • t=Test(42)
  • ```
  • The second `print` gives an error:
  • > TypeError: unsupported format string passed to Test.__format__
  • ---
  • My question is **not** about how to fix it (*I could just convert the list/dictionary/object to string, either by using [`str`](https://docs.python.org/3/library/functions.html#func-str), or by iterating through its elements or atributes and manually building the string, etc*).
  • What I want to know is **why this happens**. Why it's not possible to use format specifiers with lists, dictionaries and instances of my own classes, but if I pass them without any specifiers, it works? Are there any internal details about those types, that make them behave differently to numbers and strings, when those are formatted?
  • [1]: https://docs.python.org/3/library/stdtypes.html#str.format
#1: Initial revision by user avatar hkotsubo‭ · 2020-08-20T20:23:19Z (over 3 years ago)
Why don't format specifiers work with lists, dictionaries and other objects?
When I want to print a number or a string, I can use [*f-strings*](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) (Python >= 3.6) ou [`str.format`][1], and I can use just the variable between braces, or use [format specifiers](https://docs.python.org/3/library/string.html#formatspec). Ex:

```python
num, text = 10, 'abc'

# passing just the variables
print(f'{num} {text}')
# or
#print('{} {}'.format(num, text))

# using format specifiers
# number left-aligned, with 6 spaces, text right-aligned with 10 spaces
print(f'{num:<6} {text:>10}')
# or
#print('{:<6} {:>12}'.format(num, text))
```

Output:

```none
10 abc
10            abc
```

But if I do the same with lists or dictionaries, only the first option works:

```python
mylist = [1, 2]
dic = {'a': 1}
# this works
print(f'{mylist} {dic}')
# or
#print('{} {}'.format(mylist, dic))

# this doesn't work
print(f'{mylist:<10} {dic:>15}')
# or
#print('{:<10} {:>15}'.format(mylist, dic))
```

The first `print` outputs:

```none
[1, 2] {'a': 1}
```

But the second `print` (with the format specifiers `<10` and `>15`) gives this error:

>     TypeError: unsupported format string passed to list.__format__

---
If I try the same thing with an instance of a class that I created, the same thing occurs. Ex:

```python
class Test:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f'Test({self.value})'

t = Test(42)
print(f't={t}') # this works
print(f'{t:>10}') # this doesn't work
```

The first `print` outputs:

```none
t=Test(42)
```

The second `print` gives an error:

>     TypeError: unsupported format string passed to Test.__format__

---

My question is **not** about how to fix it (*I could just convert the list/dictionary/object to string, either by using [`str`](https://docs.python.org/3/library/functions.html#func-str), or by iterating through its elements or atributes and manually building the string, etc*).

What I want to know is **why this happens**. Why it's not possible to use format specifiers with lists, dictionaries and instances of my own classes, but if I pass them without any specifiers, it works? Are there any internal details about those types, that make them behave differently to numbers and strings, when those are formatted?


  [1]: https://docs.python.org/3/library/stdtypes.html#str.format