준호씨의 블로그

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

개발이야기

python - Number to String. String-Number concatenation

준호씨 2017. 5. 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


반응형

'개발이야기' 카테고리의 다른 글

perl - encode json  (0) 2017.05.21
How to subtract two files using grep  (0) 2017.05.18
tcping - check a specific port is open  (0) 2017.04.30
SPF should written in TXT Record (not SPF Record)  (0) 2017.04.24
iOS 점유율 확인  (0) 2017.03.10
Comments