2016-11-11 9 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

ではなくタプルを乗じ、1にも(この 'my_string.formatを行う上で' chain.from_iterable(リピート(my_tuple)) ' –

+0

@AlexHallを使用することができます* chain.from_iterable(repeat(my_tuple))) '、私のコンソールは*フリーズします*。 2.7と3の両方でチェックされました –

+0

しかし '' n''回のタプルを 'repeat(my_tuple、4)'のように繰り返さなければなりません –

関連する問題