준호씨의 블로그

python - Number to String. String-Number concatenation 본문

개발이야기

python - Number to String. String-Number concatenation

준호씨 2017.05.11 00:01

There is a number.
>>> num = 2.3
What if you want to use with string? (String-Number concatenation) You should convert number to string. There are several ways.

str function
>>> str(num)
'2.3'

repr function
>>> repr(num)
'2.3'

Backquote
>>> `num`
'2.3'

but, not in python3
>>> `num`
  File "<stdin>", line 1
    `num`
    ^
SyntaxError: invalid syntax

format
>>> "%f" % (num)
'2.300000'

pyformat
>>> '{}'.format(num)
'2.3'
>>> '{num}'.format(num=num)
'2.3'


Template
>>> from string import Template
>>> Template("$num").substitute(num=num)
'2.3'


My opinion
I would like to be able to use it with "+" operator just like Java and other languages.
"num is " + num
But python doesn't. Because python is strongly typed language.
But I still want Python to support string-number concatenation.

Anyway, except the java style, str function looks like simple way. For me, pyformat is better than old way format. And for the long sentences, Template will be useful.


References


0 Comments
댓글쓰기 폼