2016-11-11 1 views
1

최근에 다양한 길이의 튜플을 기반으로 문자열을 동적으로 형식화해야한다는 요구 사항이 있습니다. 아이디어는 문자열 포맷팅이 완료 될 때까지 반복적으로 튜플 값을 기준으로 문자열을 채우는 것입니다. 내가 좋아하는 캐릭터 라인의 내용 삽입 할다양한 숫자/길이의 값/튜플을 기반으로 동적으로 형식 문자열

"{} {} {} {} {} {}" 

: 예를 들어, 나의 문자열의 형식은 가정 해 봅시다

# For: ("hello",) 
'hello hello hello hello hello' # <- repeated "hello" 

# For: ("hello", "world") 
'hello world hello world hello' # <- repeated "hello world" 

# For: ("hello", "world", "2017") 
'hello world 2017 hello world' # <- repeated "hello world 2017" 
내가 여기에 검색

을하지만, 어떤 좋은 방법을 찾을 수 없습니다 그렇게해라, 그것을 여기에서 공유하는 생각. itertools.chain()를 사용

답변

1

: 그것은 모든 서식 문자열을 채울 때까지, 자신을 반복 계속됩니다

>>> from itertools import chain, repeat 

>>> my_string.format(*chain.from_iterable(repeat(my_tuple, 6))) 
'hello world hello world hello' 

튜플 :

>>> from itertools import chain 

>>> my_string = "{} {} {} {} {}" 
>>> my_tuple = ("hello", "world") # tuple of length 2 
>>> my_string.format(*chain(my_tuple*6)) # here 6 is some value equal to 
'hello world hello world hello'   # maximum number of time for which 
             # formatting is allowed 

또한, 우리는 또한 같은 itertools.chain.from_iterator()itertools.repeat()을 사용하여 수행 할 수 있습니다.


몇몇 다른 샘플 실행 :

# format string of 5 
>>> my_string = "{} {} {} {} {}" 

### Tuple of length 1 
>>> my_tuple = ("hello",) 
>>> my_string.format(*chain(my_tuple*6)) 
'hello hello hello hello hello' 

### Tuple of length 2 
>>> my_tuple = ("hello", "world") 
>>> my_string.format(*chain(my_tuple*6)) 
'hello world hello world hello' 

### Tuple of length 3 
>>> my_tuple = ("hello", "world", "2016") 
>>> my_string.format(*chain(my_tuple*6)) 
'hello world 2016 hello world' 
+1

튜플 곱하면, 하나는 ('chain.from_iterable (반복 (my_tuple))이'my_string.format 일을' –

+0

@AlexHall를 사용할 수 있습니다보다는 * chain.from_iterable (repeat (my_tuple)))', 내 콘솔이 * 얼어 붙습니다 *. 2.7과 3에서 모두 체크 됨 –

+0

그러나''n ''번 반복 횟수를 지정하는데 작동 함 튜플은'repeat (my_tuple, 4)'처럼 반복되어야 함 –

관련 문제