python format string을 길이를 정하지 않은 일반적인 리스트에 적용해야 할 경우 다음과 같은 방법을 사용한다.
Using string format for unknown length of argument, tuple, list
예를 들어 함수에 임의의 argument를 받은 다음, argument를 정해진 format에 따라 출력하고 싶다고
예를 들어 함수에 임의의 argument를 받은 다음, argument를 정해진 format에 따라 출력하고 싶다고
하자.
먼저, 함수에 arbitrary number of argument를 사용하려면 * 를 사용한다.
>>> def StartDance(*args):
return "%d, %d, %d, %d!" % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
하지만, 위의 경우 argument의 갯수가 4개의 경우만 format이 정해져 있기 때문에 다른 수의 argument를 넣으면 (예를 들어 (1,2) 나 (1,2,3,4,5) ) Error 가 발생한다.
이럴 때, string multiplication 과 join 을 이용할 수 있다.
>>> def StartDance(*args):
return (", ".join(["%d"] * len(args))+"!") % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
>>> StartDance(5, 6, 7, 8, 9, 10)
'5, 6, 7, 8, 9, 10!'
>>> StartDance(1)
'1!'
여기서,
(1) ["%d"]*5 는 ['%d', '%d', '%d', '%d', '%d'] 과 같다.
(2) ", ".join(['%d', '%d', '%d', '%d', '%d'] ) 는 '%d, %d, %d, %d, %d' 와 같다.
S.join(iterable) -> string Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
(3) +"!" 는 string의 마지막에 ! 를 붙여준다.
(4) tuple(args)는 주어진 args를 tuple (1,2,3,4) 로 바꾸어 준다.
아래 방법은 일일이 ['1,','2,','3,'..] 으로 list를 먼저 만든 다음에 하나의 string으로 만드는 것이고
아래 방법은 일일이 ['1,','2,','3,'..] 으로 list를 먼저 만든 다음에 하나의 string으로 만드는 것이고
print ' '.join(['%-2s' % (i,) for i in lst])
아래는 fotmat을 먼저 '%s %s %s ...' 식으로 만들어서 print 하는 것이다.
print ('%-2s ' * len(l))[:-1] % tuple(lst)
일반적으로 string multiplication을 이용하는 것이 효율적이다.
댓글 없음:
댓글 쓰기