6 ways to string objects in Python

Related: % and str.format () in Python. Which one do you use?

There was a mention of f-strings above, but I feel that it is not the only way to convert to strings. Here are some notes that you can think of.

str () and repr ()

>>> import datetime
>>> d = datetime.datetime(2017, 9, 1, 12, 12, 0, 0)
>>> str(d)
'2017-09-01 12:12:00'
>>> repr(d)
'datetime.datetime(2017, 9, 1, 12, 12)'
>>> eval(repr(d))
datetime.datetime(2017, 9, 1, 12, 12)

repr (obj) internally calls ʻobj.repr (), and str (obj) internally implements ʻobj.__str__ (), otherwise ʻobj. repr () `is called and used instead.

The result of repr (obj) is expected to be a Python expression if possible, but this is not always the case. In the datetime example above, a string that can be evaluated with ʻeval () `is returned.

There is no requirement that the result of str (obj) should be a Python expression, and it is common to prioritize a human-readable format.

When you say "convert an object into an easy-to-read string", you can think of, for example, the pprint module. It seems that it uses ʻobj.repr () . Well, it's impossible to grasp the structure from the result of __str __ ()`.

% Operator and string method str.format ()

It was the subject of the above article. I think it is the most important in everyday development, but it is omitted.

f-strings

A notation introduced in Python 3.6 that allows you to write Python expressions directly inside a string.

PEP 498 -- Literal String Interpolation

An example of FizzBuzz.

>>> print(*[f"{'Fizz'*(not i%3)}{'Buzz'*(not i%5)}" or i for i in range(1,31)], sep='\n')
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz

I refer to Reddit's "a Py3.6 fizzBuzz oneliner with f-strings", but map () I changed to using list comprehension rather than using list comprehension recently, so I changed it (reduce () may have dropped the library).

Just in case, the * at the beginning of the argument ofprint ()indicates the unpacking of the list.

In terms of type checking, at least mypy 0.521 looks inside f-strings.

$ mypy --version
mypy 0.521
$ cat /tmp/test.py
def func(a: int) -> int:
    return a ** 2

print(f'{func(10.0)}')
$ python /tmp/test.py
100.0
$ mypy /tmp/test.py
/tmp/test.py:4: error: Argument 1 to "func" has incompatible type "float"; expected "int"

Unfortunately, I often use 3.5 or earlier, so I haven't taken the initiative to unify it. However, in the future, I think there is a possibility that f-strings will become the center, overcoming str.format ().

Template string

[https://docs.python.jp/3/library/string.html#template-strings](template string)

The old-fashioned feature of template strings is to replace $ variables, which is built into Python. I will briefly introduce the above sample.

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

Unfortunately, HTML escaping etc. are not supported. I rarely see it personally, but I have considered using it.

Other

The title says six, but there are still some standard Python features.

There should be other ways to stringify using an external library such as jinja2. Of course, if you make it yourself, you will have more choices.

Recommended Posts

6 ways to string objects in Python
String manipulation in python
3 ways to parse time strings in python [Note]
How to embed a variable in a python string
[python] Convert date to string
To flush stdout in Python
String object methods in Python
Equivalence of objects in Python
Speech to speech in python [text to speech]
String date manipulation in Python
How to develop in Python
Post to Slack in Python
Parse a JSON string written to a file in Python
How to convert / restore a string with [] in python
I want to embed a variable in a Python string
How to write string concatenation in multiple lines in Python
[Python] How to expand variables in a character string
Preparing to script control Rhino objects in Grasshopper / Python
[Python] How to do PCA in Python
Convert markdown to PDF in Python
How to collect images in Python
In the python command python points to python3.8
Assignments and changes in Python objects
Various ways to calculate the similarity between data in python
Try to calculate Trace in Python
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
Python string
Examine the object's class in python
5 Ways to Create a Python Chatbot
Create a random string in Python
How to handle Japanese in Python
An alternative to `pause` in Python
How to make a string into an array or an array into a string in Python
How to get a string from a command line argument in python
Timezone specification when converting a string to datetime type in python
Various ways to create an array of numbers from 1 to 10 in Python.
I tried to implement PLSA in Python
Conversion of string <-> date (date, datetime) in Python
[Introduction to Python] How to use class in Python?
Try logging in to qiita with Python
Install Pyaudio to play wave in python
How to access environment variables in Python
I tried to implement permutation in Python
Method to build Python environment in Xcode 6
How to dynamically define variables in Python
How to do R chartr () in Python
Pin current directory to script directory in Python
[Itertools.permutations] How to put permutations in Python
PUT gzip directly to S3 in Python
Send email to multiple recipients in Python (Python 3)
Convert psd file to png in Python
Sample script to trap signals in Python
I tried to implement PLSA in Python 2
To set default encoding to utf-8 in python
Decorator to avoid UnicodeEncodeError in Python 3 print ()
[Python] How to invert a character string
Log in to Slack using requests in Python
How to get a stacktrace in python