부분 문자열 형식 지정
template 와 유사한 이 합니까?safe_substitute()
기능?
예:
s = '{foo} {bar}'
s.format(foo='FOO') #Problem: raises KeyError 'bar'
당신은 사용할 수 있습니다.partial
에서 합니다.functools
이는 짧고 읽기 쉬우며 코더의 의도를 설명합니다.
from functools import partial
s = partial("{foo} {bar}".format, foo="FOO")
print s(bar="BAR")
# FOO BAR
형식을 지정하는 순서를 알고 있는 경우:
s = '{foo} {{bar}}'
다음과 같이 사용합니다.
ss = s.format(foo='FOO')
print ss
>>> 'FOO {bar}'
print ss.format(bar='BAR')
>>> 'FOO BAR'
수 .foo
그리고.bar
동시에 순차적으로 해야 합니다.
매핑을 덮어씀으로써 부분 포맷으로 속일 수 있습니다.
import string
class FormatDict(dict):
def __missing__(self, key):
return "{" + key + "}"
s = '{foo} {bar}'
formatter = string.Formatter()
mapping = FormatDict(foo='FOO')
print(formatter.vformat(s, (), mapping))
인쇄술
FOO {bar}
물론 이 기본 구현은 기본적인 경우에만 올바르게 작동합니다.
은 의이한 사항제입니다..format()
부분 치환을 할 수 없다는 것이 저를 괴롭히고 있습니다.
정의 한 후Formatter
여기에 나와 있는 많은 답변에 설명된 클래스와 lazy_format과 같은 타사 패키지를 사용하는 것을 고려하더라도 훨씬 간단한 내장 솔루션을 발견했습니다.템플릿 문자열
도 부분 을 통해 부분 치환을 합니다.safe_substitute()
방법.템플릿 문자열에는 다음이 있어야 합니다.$
접두사(약간 이상하게 느껴지지만 전반적인 해결책이 더 낫다고 생각합니다.)
import string
template = string.Template('${x} ${y}')
try:
template.substitute({'x':1}) # raises KeyError
except KeyError:
pass
# but the following raises no error
partial_str = template.safe_substitute({'x':1}) # no error
# partial_str now contains a string with partial substitution
partial_template = string.Template(partial_str)
substituted_str = partial_template.safe_substitute({'y':2}) # no error
print substituted_str # prints '12'
다음을 기반으로 편의성 래퍼 구성:
class StringTemplate(object):
def __init__(self, template):
self.template = string.Template(template)
self.partial_substituted_str = None
def __repr__(self):
return self.template.safe_substitute()
def format(self, *args, **kws):
self.partial_substituted_str = self.template.safe_substitute(*args, **kws)
self.template = string.Template(self.partial_substituted_str)
return self.__repr__()
>>> s = StringTemplate('${x}${y}')
>>> s
'${x}${y}'
>>> s.format(x=1)
'1${y}'
>>> s.format({'y':2})
'12'
>>> print s
12
마찬가지로 기본 문자열 형식을 사용하는 스벤의 응답에 기반한 래퍼:
class StringTemplate(object):
class FormatDict(dict):
def __missing__(self, key):
return "{" + key + "}"
def __init__(self, template):
self.substituted_str = template
self.formatter = string.Formatter()
def __repr__(self):
return self.substituted_str
def format(self, *args, **kwargs):
mapping = StringTemplate.FormatDict(*args, **kwargs)
self.substituted_str = self.formatter.vformat(self.substituted_str, (), mapping)
이것이 빠른 해결책으로 괜찮은지는 잘 모르겠지만, 어때요?
s = '{foo} {bar}'
s.format(foo='FOO', bar='{bar}')
? :)
이 당신 자신을 한다면,Formatter
그것은 그것을 무시합니다.get_value
데 할 수 .
http://docs.python.org/library/string.html#string.Formatter.get_value
예를 들어, 당신은 지도를 만들 수 있습니다.bar
"{bar}"
한다면bar
크워그에 있지 않습니다.
그렇게 그나위, 해야 합니다.format()
"Formatter"가 아닌 " 개체의 format()
방법.
>>> 'fd:{uid}:{{topic_id}}'.format(uid=123)
'fd:123:{topic_id}'
이거 한번 해보세요.
Amber의 의견 덕분에 저는 다음과 같은 생각을 하게 되었습니다.
import string
try:
# Python 3
from _string import formatter_field_name_split
except ImportError:
formatter_field_name_split = str._formatter_field_name_split
class PartialFormatter(string.Formatter):
def get_field(self, field_name, args, kwargs):
try:
val = super(PartialFormatter, self).get_field(field_name, args, kwargs)
except (IndexError, KeyError, AttributeError):
first, _ = formatter_field_name_split(field_name)
val = '{' + field_name + '}', first
return val
제가 찾은 모든 솔루션은 고급 사양 또는 변환 옵션에 문제가 있는 것 같습니다.@Seven Marnach의 Format Placeholder는 놀라울 정도로 영리하지만 강제로 작동하지 않습니다(예:{a!s:>2s}
) 왜냐하면 그것은 그것을 부르기 때문입니다.__str__
에서는) 법이대(이 예에서는) 신방는 대신 방법을 __format__
추가 서식이 손실됩니다.
다음은 제가 최종적으로 수행한 작업과 주요 기능 중 일부입니다.
sformat('The {} is {}', 'answer')
'The answer is {}'
sformat('The answer to {question!r} is {answer:0.2f}', answer=42)
'The answer to {question!r} is 42.00'
sformat('The {} to {} is {:0.{p}f}', 'answer', 'everything', p=4)
'The answer to everything is {:0.4f}'
- 는 와유인이제다공니와 합니다.
str.format
한 매핑이 ) - 보다 복잡한 포맷 옵션을 지원합니다.
- 강압적인 요
{k!s}
{!r}
- 둥지를 틀다
{k:>{size}}
- 을 느끼다 끌리
{k.foo}
- 아이템 획득
{k[0]}
- + 지정 제 + 식지정
{k!s:>{size}}
- 강압적인 요
import string
class SparseFormatter(string.Formatter):
"""
A modified string formatter that handles a sparse set of format
args/kwargs.
"""
# re-implemented this method for python2/3 compatibility
def vformat(self, format_string, args, kwargs):
used_args = set()
result, _ = self._vformat(format_string, args, kwargs, used_args, 2)
self.check_unused_args(used_args, args, kwargs)
return result
def _vformat(self, format_string, args, kwargs, used_args, recursion_depth,
auto_arg_index=0):
if recursion_depth < 0:
raise ValueError('Max string recursion exceeded')
result = []
for literal_text, field_name, format_spec, conversion in \
self.parse(format_string):
orig_field_name = field_name
# output the literal text
if literal_text:
result.append(literal_text)
# if there's a field, output it
if field_name is not None:
# this is some markup, find the object and do
# the formatting
# handle arg indexing when empty field_names are given.
if field_name == '':
if auto_arg_index is False:
raise ValueError('cannot switch from manual field '
'specification to automatic field '
'numbering')
field_name = str(auto_arg_index)
auto_arg_index += 1
elif field_name.isdigit():
if auto_arg_index:
raise ValueError('cannot switch from manual field '
'specification to automatic field '
'numbering')
# disable auto arg incrementing, if it gets
# used later on, then an exception will be raised
auto_arg_index = False
# given the field_name, find the object it references
# and the argument it came from
try:
obj, arg_used = self.get_field(field_name, args, kwargs)
except (IndexError, KeyError):
# catch issues with both arg indexing and kwarg key errors
obj = orig_field_name
if conversion:
obj += '!{}'.format(conversion)
if format_spec:
format_spec, auto_arg_index = self._vformat(
format_spec, args, kwargs, used_args,
recursion_depth, auto_arg_index=auto_arg_index)
obj += ':{}'.format(format_spec)
result.append('{' + obj + '}')
else:
used_args.add(arg_used)
# do any conversion on the resulting object
obj = self.convert_field(obj, conversion)
# expand the format spec, if needed
format_spec, auto_arg_index = self._vformat(
format_spec, args, kwargs,
used_args, recursion_depth-1,
auto_arg_index=auto_arg_index)
# format the object and append to the result
result.append(self.format_field(obj, format_spec))
return ''.join(result), auto_arg_index
def sformat(s, *args, **kwargs):
# type: (str, *Any, **Any) -> str
"""
Sparse format a string.
Parameters
----------
s : str
args : *Any
kwargs : **Any
Examples
--------
>>> sformat('The {} is {}', 'answer')
'The answer is {}'
>>> sformat('The answer to {question!r} is {answer:0.2f}', answer=42)
'The answer to {question!r} is 42.00'
>>> sformat('The {} to {} is {:0.{p}f}', 'answer', 'everything', p=4)
'The answer to everything is {:0.4f}'
Returns
-------
str
"""
return SparseFormatter().format(s, *args, **kwargs)
저는 이 방법이 어떻게 작동하기를 원하는지에 대한 몇 가지 테스트를 작성한 후 다양한 구현의 문제를 발견했습니다.그들이 통찰력이 있다고 생각하는 사람이 있다면, 그들은 아래에 있습니다.
import pytest
def test_auto_indexing():
# test basic arg auto-indexing
assert sformat('{}{}', 4, 2) == '42'
assert sformat('{}{} {}', 4, 2) == '42 {}'
def test_manual_indexing():
# test basic arg indexing
assert sformat('{0}{1} is not {1} or {0}', 4, 2) == '42 is not 2 or 4'
assert sformat('{0}{1} is {3} {1} or {0}', 4, 2) == '42 is {3} 2 or 4'
def test_mixing_manualauto_fails():
# test mixing manual and auto args raises
with pytest.raises(ValueError):
assert sformat('{!r} is {0}{1}', 4, 2)
def test_kwargs():
# test basic kwarg
assert sformat('{base}{n}', base=4, n=2) == '42'
assert sformat('{base}{n}', base=4, n=2, extra='foo') == '42'
assert sformat('{base}{n} {key}', base=4, n=2) == '42 {key}'
def test_args_and_kwargs():
# test mixing args/kwargs with leftovers
assert sformat('{}{k} {v}', 4, k=2) == '42 {v}'
# test mixing with leftovers
r = sformat('{}{} is the {k} to {!r}', 4, 2, k='answer')
assert r == '42 is the answer to {!r}'
def test_coercion():
# test coercion is preserved for skipped elements
assert sformat('{!r} {k!r}', '42') == "'42' {k!r}"
def test_nesting():
# test nesting works with or with out parent keys
assert sformat('{k:>{size}}', k=42, size=3) == ' 42'
assert sformat('{k:>{size}}', size=3) == '{k:>3}'
@pytest.mark.parametrize(
('s', 'expected'),
[
('{a} {b}', '1 2.0'),
('{z} {y}', '{z} {y}'),
('{a} {a:2d} {a:04d} {y:2d} {z:04d}', '1 1 0001 {y:2d} {z:04d}'),
('{a!s} {z!s} {d!r}', '1 {z!s} {\'k\': \'v\'}'),
('{a!s:>2s} {z!s:>2s}', ' 1 {z!s:>2s}'),
('{a!s:>{a}s} {z!s:>{z}s}', '1 {z!s:>{z}s}'),
('{a.imag} {z.y}', '0 {z.y}'),
('{e[0]:03d} {z[0]:03d}', '042 {z[0]:03d}'),
],
ids=[
'normal',
'none',
'formatting',
'coercion',
'formatting+coercion',
'nesting',
'getattr',
'getitem',
]
)
def test_sformat(s, expected):
# test a bunch of random stuff
data = dict(
a=1,
b=2.0,
c='3',
d={'k': 'v'},
e=[42],
)
assert expected == sformat(s, **data)
저는 이 정도면 충분했습니다.
>>> ss = 'dfassf {} dfasfae efaef {} fds'
>>> nn = ss.format('f1', '{}')
>>> nn
'dfassf f1 dfasfae efaef {} fds'
>>> n2 = nn.format('whoa')
>>> n2
'dfassf f1 dfasfae efaef whoa fds'
제 제안은 다음과 같습니다(Python 3.6으로 테스트됨).
class Lazymap(object):
def __init__(self, **kwargs):
self.dict = kwargs
def __getitem__(self, key):
return self.dict.get(key, "".join(["{", key, "}"]))
s = '{foo} {bar}'
s.format_map(Lazymap(bar="FOO"))
# >>> '{foo} FOO'
s.format_map(Lazymap(bar="BAR"))
# >>> '{foo} BAR'
s.format_map(Lazymap(bar="BAR", foo="FOO", baz="BAZ"))
# >>> 'FOO BAR'
업데이트: 훨씬 더 우아한 방법(하위 분류)dict
과부하 ㅠㅠㅠ__missing__(self, key)
)는 다음과 같습니다. https://stackoverflow.com/a/17215533/333403
인수를 전달할 사전의 압축을 풀고 싶은 경우format
이와 관련된 질문과 같이, 당신은 다음 방법을 사용할 수 있습니다.
먼저 문자열을 가정합니다.s
다음 질문과 동일합니다.
s = '{foo} {bar}'
값은 다음 사전에 의해 제공됩니다.
replacements = {'foo': 'FOO'}
분명히 이것은 작동하지 않을 것입니다.
s.format(**replacements)
#---------------------------------------------------------------------------
#KeyError Traceback (most recent call last)
#<ipython-input-29-ef5e51de79bf> in <module>()
#----> 1 s.format(**replacements)
#
#KeyError: 'bar'
그러나 먼저 명명된 모든 인수를 가져와 인수를 곱슬곱슬하게 묶은 자체에 매핑하는 사전을 만들 수 있습니다.
from string import Formatter
args = {x[1]:'{'+x[1]+'}' for x in Formatter().parse(s)}
print(args)
#{'foo': '{foo}', 'bar': '{bar}'}
이제 다음을 사용합니다.args
를 사된키 전는우로 채우는 replacements
python 3.5+의 경우 다음과 같은 단일 식을 사용할 수 있습니다.
new_s = s.format(**{**args, **replacements}}
print(new_s)
#'FOO {bar}'
이전 버전의 파이썬의 경우, 당신은 다음과 같이 부를 수 있습니다.update
:
args.update(replacements)
print(s.format(**args))
#'FOO {bar}'
이것은 약간 엉성한 정규식 기반 솔루션입니다.이는 다음과 같은 중첩 형식 지정자에서는 작동하지 않습니다.{foo:{width}}
하지만 그것은 다른 대답들이 가지고 있는 문제들 중 일부를 고칩니다.
def partial_format(s, **kwargs):
parts = re.split(r'(\{[^}]*\})', s)
for k, v in kwargs.items():
for idx, part in enumerate(parts):
if re.match(rf'\{{{k}[!:}}]', part): # Placeholder keys must always be followed by '!', ':', or the closing '}'
parts[idx] = parts[idx].format_map({k: v})
return ''.join(parts)
# >>> partial_format('{foo} {bar:1.3f}', foo='FOO')
# 'FOO {bar:1.3f}'
# >>> partial_format('{foo} {bar:1.3f}', bar=1)
# '{foo} 1.000'
문자열이 완전히 채워질 때까지 사용하지 않을 것이라고 가정하면 다음 클래스와 같은 작업을 수행할 수 있습니다.
class IncrementalFormatting:
def __init__(self, string):
self._args = []
self._kwargs = {}
self._string = string
def add(self, *args, **kwargs):
self._args.extend(args)
self._kwargs.update(kwargs)
def get(self):
return self._string.format(*self._args, **self._kwargs)
예:
template = '#{a}:{}/{}?{c}'
message = IncrementalFormatting(template)
message.add('abc')
message.add('xyz', a=24)
message.add(c='lmno')
assert message.get() == '#24:abc/xyz?lmno'
이를 달성하는 한 가지 방법이 더 있습니다. 즉, 다음을 사용하여format
그리고.%
변수를 대체합니다.예:
>>> s = '{foo} %(bar)s'
>>> s = s.format(foo='my_foo')
>>> s
'my_foo %(bar)s'
>>> s % {'bar': 'my_bar'}
'my_foo my_bar'
매우 추악하지만 저에게 가장 간단한 해결책은 그냥 하는 것입니다.
tmpl = '{foo}, {bar}'
tmpl.replace('{bar}', 'BAR')
Out[3]: '{foo}, BAR'
이 방법으로 여전히 사용할 수 있습니다.tmpl
일반 템플릿으로 사용하고 필요한 경우에만 부분 형식 지정을 수행합니다.저는 이 문제가 너무 사소한 것이라 생각해서 모한 라즈와 같은 과잉 살상 솔루션을 사용할 수 없습니다.
여기저기서 가장 유망한 솔루션을 테스트해 본 결과, 다음과 같은 요구 사항을 충족하는 솔루션은 단 하나도 없다는 것을 깨달았습니다.
그래서 저는 위의 요구 사항을 충족하는 저만의 해결책을 작성했습니다.(편집: 이제 이 답변에서 보고된 것처럼 @SvenMarnach의 버전은 제가 필요로 하는 코너 케이스를 처리하는 것 같습니다.)
문자열을 구문 하여 일치하는 중첩된 로적저는, 문자을템열구문분릿을 찾았습니다.{.*?}
(으)로 )find_all()
헬퍼 기능) 및 를 사용하여 점진적으로 직접 포맷된 문자열을 작성합니다.str.format_map()
.KeyError
.
def find_all(
text,
pattern,
overlap=False):
"""
Find all occurrencies of the pattern in the text.
Args:
text (str|bytes|bytearray): The input text.
pattern (str|bytes|bytearray): The pattern to find.
overlap (bool): Detect overlapping patterns.
Yields:
position (int): The position of the next finding.
"""
len_text = len(text)
offset = 1 if overlap else (len(pattern) or 1)
i = 0
while i < len_text:
i = text.find(pattern, i)
if i >= 0:
yield i
i += offset
else:
break
def matching_delimiters(
text,
l_delim,
r_delim,
including=True):
"""
Find matching delimiters in a sequence.
The delimiters are matched according to nesting level.
Args:
text (str|bytes|bytearray): The input text.
l_delim (str|bytes|bytearray): The left delimiter.
r_delim (str|bytes|bytearray): The right delimiter.
including (bool): Include delimeters.
yields:
result (tuple[int]): The matching delimiters.
"""
l_offset = len(l_delim) if including else 0
r_offset = len(r_delim) if including else 0
stack = []
l_tokens = set(find_all(text, l_delim))
r_tokens = set(find_all(text, r_delim))
positions = l_tokens.union(r_tokens)
for pos in sorted(positions):
if pos in l_tokens:
stack.append(pos + 1)
elif pos in r_tokens:
if len(stack) > 0:
prev = stack.pop()
yield (prev - l_offset, pos + r_offset, len(stack))
else:
raise ValueError(
'Found `{}` unmatched right token(s) `{}` (position: {}).'
.format(len(r_tokens) - len(l_tokens), r_delim, pos))
if len(stack) > 0:
raise ValueError(
'Found `{}` unmatched left token(s) `{}` (position: {}).'
.format(
len(l_tokens) - len(r_tokens), l_delim, stack.pop() - 1))
def safe_format_map(
text,
source):
"""
Perform safe string formatting from a mapping source.
If a value is missing from source, this is simply ignored, and no
`KeyError` is raised.
Args:
text (str): Text to format.
source (Mapping|None): The mapping to use as source.
If None, uses caller's `vars()`.
Returns:
result (str): The formatted text.
"""
stack = []
for i, j, depth in matching_delimiters(text, '{', '}'):
if depth == 0:
try:
replacing = text[i:j].format_map(source)
except KeyError:
pass
else:
stack.append((i, j, replacing))
result = ''
i, j = len(text), 0
while len(stack) > 0:
last_i = i
i, j, replacing = stack.pop()
result = replacing + text[j:last_i] + result
if i > 0:
result = text[0:i] + result
return result
(이 코드는 FlyingCircus -- 고지 사항:제가 그것의 주요 저자입니다.)
이 코드의 용도는 다음과 같습니다.
print(safe_format_map('{a} {b} {c}', dict(a=-A-)))
# -A- {b} {c}
제가 가장 좋아하는 솔루션과 비교해 보겠습니다(여기 저기서 친절하게 코드를 공유한 @Sven Marnach).
import string
class FormatPlaceholder:
def __init__(self, key):
self.key = key
def __format__(self, spec):
result = self.key
if spec:
result += ":" + spec
return "{" + result + "}"
def __getitem__(self, index):
self.key = "{}[{}]".format(self.key, index)
return self
def __getattr__(self, attr):
self.key = "{}.{}".format(self.key, attr)
return self
class FormatDict(dict):
def __missing__(self, key):
return FormatPlaceholder(key)
def safe_format_alt(text, source):
formatter = string.Formatter()
return formatter.vformat(text, (), FormatDict(source))
다음은 몇 가지 테스트입니다.
test_texts = (
'{b} {f}', # simple nothing useful in source
'{a} {b}', # simple
'{a} {b} {c:5d}', # formatting
'{a} {b} {c!s}', # coercion
'{a} {b} {c!s:>{a}s}', # formatting and coercion
'{a} {b} {c:0{a}d}', # nesting
'{a} {b} {d[x]}', # dicts (existing in source)
'{a} {b} {e.index}', # class (existing in source)
'{a} {b} {f[g]}', # dict (not existing in source)
'{a} {b} {f.values}', # class (not existing in source)
)
source = dict(a=4, c=101, d=dict(x='FOO'), e=[])
실행할 수 있는 코드:
funcs = safe_format_map, safe_format_alt
n = 18
for text in test_texts:
full_source = {**dict(b='---', f=dict(g='Oh yes!')), **source}
print('{:>{n}s} : OK : '.format('str.format_map', n=n) + text.format_map(full_source))
for func in funcs:
try:
print(f'{func.__name__:>{n}s} : OK : ' + func(text, source))
except:
print(f'{func.__name__:>{n}s} : FAILED : {text}')
결과:
str.format_map : OK : --- {'g': 'Oh yes!'}
safe_format_map : OK : {b} {f}
safe_format_alt : OK : {b} {f}
str.format_map : OK : 4 ---
safe_format_map : OK : 4 {b}
safe_format_alt : OK : 4 {b}
str.format_map : OK : 4 --- 101
safe_format_map : OK : 4 {b} 101
safe_format_alt : OK : 4 {b} 101
str.format_map : OK : 4 --- 101
safe_format_map : OK : 4 {b} 101
safe_format_alt : OK : 4 {b} 101
str.format_map : OK : 4 --- 101
safe_format_map : OK : 4 {b} 101
safe_format_alt : OK : 4 {b} 101
str.format_map : OK : 4 --- 0101
safe_format_map : OK : 4 {b} 0101
safe_format_alt : OK : 4 {b} 0101
str.format_map : OK : 4 --- FOO
safe_format_map : OK : 4 {b} FOO
safe_format_alt : OK : 4 {b} FOO
str.format_map : OK : 4 --- <built-in method index of list object at 0x7f7a485666c8>
safe_format_map : OK : 4 {b} <built-in method index of list object at 0x7f7a485666c8>
safe_format_alt : OK : 4 {b} <built-in method index of list object at 0x7f7a485666c8>
str.format_map : OK : 4 --- Oh yes!
safe_format_map : OK : 4 {b} {f[g]}
safe_format_alt : OK : 4 {b} {f[g]}
str.format_map : OK : 4 --- <built-in method values of dict object at 0x7f7a485da090>
safe_format_map : OK : 4 {b} {f.values}
safe_format_alt : OK : 4 {b} {f.values}
보시다시피, 업데이트된 버전은 이전 버전이 실패했던 코너 케이스를 잘 처리하는 것 같습니다.
시간적으로, 실제에 따라 서로의 약 50% 이내에 있습니다.text
실제 포그맷아실제도마고리그▁the(▁()▁to실제andsource
), 그러나safe_format_map()
제가 수행한 대부분의 테스트에서 우위에 있는 것 같습니다(물론 의미가 무엇이든).
for text in test_texts:
print(f' {text}')
%timeit safe_format(text * 1000, source)
%timeit safe_format_alt(text * 1000, source)
{b} {f}
3.93 ms ± 153 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
6.35 ms ± 51.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b}
4.37 ms ± 57.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.2 ms ± 159 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {c:5d}
7.15 ms ± 91.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.76 ms ± 69.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {c!s}
7.04 ms ± 138 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.56 ms ± 161 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {c!s:>{a}s}
8.91 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
10.5 ms ± 181 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {c:0{a}d}
8.84 ms ± 147 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
10.2 ms ± 202 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {d[x]}
7.01 ms ± 197 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.35 ms ± 106 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {e.index}
11 ms ± 68.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.78 ms ± 405 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {f[g]}
6.55 ms ± 88.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
9.12 ms ± 159 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{a} {b} {f.values}
6.61 ms ± 55.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
9.92 ms ± 98.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
저는 @sven-marnach 답변을 좋아합니다.제 대답은 단순히 그것의 확장된 버전입니다.키워드가 아닌 형식을 지정할 수 있으며 추가 키는 무시됩니다.다음은 사용 예입니다(함수의 이름은 python 3.6 f-string 포맷에 대한 참조).
# partial string substitution by keyword
>>> f('{foo} {bar}', foo="FOO")
'FOO {bar}'
# partial string substitution by argument
>>> f('{} {bar}', 1)
'1 {bar}'
>>> f('{foo} {}', 1)
'{foo} 1'
# partial string substitution with arguments and keyword mixed
>>> f('{foo} {} {bar} {}', '|', bar='BAR')
'{foo} | BAR {}'
# partial string substitution with extra keyword
>>> f('{foo} {bar}', foo="FOO", bro="BRO")
'FOO {bar}'
# you can simply 'pour out' your dictionary to format function
>>> kwargs = {'foo': 'FOO', 'bro': 'BRO'}
>>> f('{foo} {bar}', **kwargs)
'FOO {bar}'
내 코드는 다음과 같습니다.
from string import Formatter
class FormatTuple(tuple):
def __getitem__(self, key):
if key + 1 > len(self):
return "{}"
return tuple.__getitem__(self, key)
class FormatDict(dict):
def __missing__(self, key):
return "{" + key + "}"
def f(string, *args, **kwargs):
"""
String safe substitute format method.
If you pass extra keys they will be ignored.
If you pass incomplete substitute map, missing keys will be left unchanged.
:param string:
:param kwargs:
:return:
>>> f('{foo} {bar}', foo="FOO")
'FOO {bar}'
>>> f('{} {bar}', 1)
'1 {bar}'
>>> f('{foo} {}', 1)
'{foo} 1'
>>> f('{foo} {} {bar} {}', '|', bar='BAR')
'{foo} | BAR {}'
>>> f('{foo} {bar}', foo="FOO", bro="BRO")
'FOO {bar}'
"""
formatter = Formatter()
args_mapping = FormatTuple(args)
mapping = FormatDict(kwargs)
return formatter.vformat(string, args_mapping, mapping)
만약 당신이 많은 템플릿을 만들고 있고 Python의 내장된 문자열 템플릿 기능이 불충분하거나 투박하다는 것을 발견한다면, Jinja2를 보세요.
문서에서:
Jinja는 Django의 템플릿을 본뜬 Python을 위한 현대적이고 디자이너 친화적인 템플릿 언어입니다.
@Sam Bourne 댓글을 읽으면서, 나는 @Sven Marnach의 코드를 강제로 적절하게 작동하도록 수정했습니다(예:{a!s:>2s}
파서를 사용할 수 있습니다 사용자 정의 파서를 작성하지 않습니다.기본 아이디어는 문자열로 변환하는 것이 아니라 누락된 키를 강제 태그와 연결하는 것입니다.
import string
class MissingKey(object):
def __init__(self, key):
self.key = key
def __str__(self): # Supports {key!s}
return MissingKeyStr("".join([self.key, "!s"]))
def __repr__(self): # Supports {key!r}
return MissingKeyStr("".join([self.key, "!r"]))
def __format__(self, spec): # Supports {key:spec}
if spec:
return "".join(["{", self.key, ":", spec, "}"])
return "".join(["{", self.key, "}"])
def __getitem__(self, i): # Supports {key[i]}
return MissingKey("".join([self.key, "[", str(i), "]"]))
def __getattr__(self, name): # Supports {key.name}
return MissingKey("".join([self.key, ".", name]))
class MissingKeyStr(MissingKey, str):
def __init__(self, key):
if isinstance(key, MissingKey):
self.key = "".join([key.key, "!s"])
else:
self.key = key
class SafeFormatter(string.Formatter):
def __init__(self, default=lambda k: MissingKey(k)):
self.default=default
def get_value(self, key, args, kwds):
if isinstance(key, str):
return kwds.get(key, self.default(key))
else:
return super().get_value(key, args, kwds)
다음과 같이 사용(예:
SafeFormatter().format("{a:<5} {b:<10}", a=10)
을 받아)는인 @norok2(@norok2영감을받아확다니출인합력을존스테의음서에트스테▁the▁for는▁the▁output▁(다▁the@니▁following확합al▁traditionnor인)(▁frominspired다음▁check)▁@▁tests▁tests아출▁by을력받의.format_map
a 리고a.safe_format_map
올바른 키워드를 제공하거나 키워드를 사용하지 않는 두 가지 경우에 위의 클래스를 기반으로 합니다.
def safe_format_map(text, source):
return SafeFormatter().format(text, **source)
test_texts = (
'{a} ', # simple nothing useful in source
'{a:5d}', # formatting
'{a!s}', # coercion
'{a!s:>{a}s}', # formatting and coercion
'{a:0{a}d}', # nesting
'{d[x]}', # indexing
'{d.values}', # member
)
source = dict(a=10,d=dict(x='FOO'))
funcs = [safe_format_map,
str.format_map
#safe_format_alt # Version based on parsing (See @norok2)
]
n = 18
for text in test_texts:
# full_source = {**dict(b='---', f=dict(g='Oh yes!')), **source}
# print('{:>{n}s} : OK : '.format('str.format_map', n=n) + text.format_map(full_source))
print("Testing:", text)
for func in funcs:
try:
print(f'{func.__name__:>{n}s} : OK\t\t\t: ' + func(text, dict()))
except:
print(f'{func.__name__:>{n}s} : FAILED')
try:
print(f'{func.__name__:>{n}s} : OK\t\t\t: ' + func(text, source))
except:
print(f'{func.__name__:>{n}s} : FAILED')
어떤 출력
Testing: {a}
safe_format_map : OK : {a}
safe_format_map : OK : 10
format_map : FAILED
format_map : OK : 10
Testing: {a:5d}
safe_format_map : OK : {a:5d}
safe_format_map : OK : 10
format_map : FAILED
format_map : OK : 10
Testing: {a!s}
safe_format_map : OK : {a!s}
safe_format_map : OK : 10
format_map : FAILED
format_map : OK : 10
Testing: {a!s:>{a}s}
safe_format_map : OK : {a!s:>{a}s}
safe_format_map : OK : 10
format_map : FAILED
format_map : OK : 10
Testing: {a:0{a}d}
safe_format_map : OK : {a:0{a}d}
safe_format_map : OK : 0000000010
format_map : FAILED
format_map : OK : 0000000010
Testing: {d[x]}
safe_format_map : OK : {d[x]}
safe_format_map : OK : FOO
format_map : FAILED
format_map : OK : FOO
Testing: {d.values}
safe_format_map : OK : {d.values}
safe_format_map : OK : <built-in method values of dict object at 0x7fe61e230af8>
format_map : FAILED
format_map : OK : <built-in method values of dict object at 0x7fe61e230af8>
TL;DR: 문제:defaultdict
에 대해 실패합니다.{foobar[a]}
한다면foobar
설정되지 않음:
from collections import defaultdict
text = "{bar}, {foo}, {foobar[a]}" # {bar} is set, {foo} is "", {foobar[a]} fails
text.format_map(defaultdict(str, bar="A")) # TypeError: string indices must be integers
솔루션:알았다.DefaultWrapper
편집에서 클래스를 선택한 다음:
text = "{bar}, {foo}, {foobar[a]}"
text.format_map(DefaultWrapper(bar="A")) # "A, , " (missing replaced with empty str)
# Even this works:
foobar = {"c": "C"}
text = "{foobar[a]}, {foobar[c]}"
text.format_map(DefaultWrapper(foobar=foobar)) # ", C" missing indices are also replaced
게시된 솔루션 중 하나에서 인덱싱 및 특성 액세스가 작동하지 않습니다.다음 코드는 a를 발생시킵니다.
from collections import defaultdict
text = "{foo} '{bar[index]}'"
text.format_map(defaultdict(str, foo="FOO")) # raises a TypeError
이 문제를 해결하려면 인덱싱을 지원하는 사용자 지정 기본값 개체와 함께 솔루션을 사용할 수 있습니다.그DefaultWrapper
object는 오류 없이 무제한으로 속성을 인덱싱/사용할 수 있는 인덱스 및 속성 액세스에서 자체를 반환합니다.
요청된 값의 일부를 포함하는 컨테이너를 허용하도록 이 값을 확장할 수 있습니다.아래의 편집을 확인하십시오.
class DefaultWrapper:
def __repr__(self):
return "Empty default value"
def __str__(self):
return ""
def __format__(self, format_spec):
return ""
def __getattr__(self, name):
return self
def __getitem__(self, name):
return self
def __contains__(self, name):
return True
text = "'{foo}', '{bar[index][i]}'"
print(text.format_map(defaultdict(DefaultWrapper, foo="FOO")))
# 'FOO', ''
편집: 부분적으로 채워진 용기
위 클래스는 부분적으로 채워진 컨테이너를 지원하도록 확장될 수 있습니다.그래서 예를 들면,
text = "'{foo[a]}', '{foo[b]}'"
foo = {"a": "A"}
print(text.format_map(defaultdict(DefaultWrapper, foo=foo)))
# KeyError: 'b'
그 아이디어는 그것을 대체하는 것입니다.defaultdict
▁the.DefaultWrapper
.DefaultWrapper
물체가 그 주위를 감싼다.container
(""으로 ")DefaultWrapper
또는 컨테이너를 문자열로 지정할 수 있습니다.이렇게 하면 맵의 무한 깊이가 모방되지만 현재 값은 모두 반환됩니다.
그kwargs
편의를 위해 추가되었습니다.이런 식으로 하면 더 비슷해 보입니다.defaultdict
해결책
class DefaultWrapper:
"""A wrapper around the `container` to allow accessing with a default value."""
ignore_str_format_errors = True
def __init__(self, container="", **kwargs):
self.container = container
self.kwargs = kwargs
def __repr__(self):
return "DefaultWrapper around '{}'".format(repr(self.container))
def __str__(self):
return str(self.container)
def __format__(self, format_spec):
try:
return self.container.__format__(format_spec)
except TypeError as e:
if DefaultWrapper.ignore_str_format_errors or self.container == "":
return str(self)
else:
raise e
def __getattr__(self, name):
try:
return DefaultWrapper(getattr(self.container, name))
except AttributeError:
return DefaultWrapper()
def __getitem__(self, name):
try:
return DefaultWrapper(self.container[name])
except (TypeError, LookupError):
try:
return DefaultWrapper(self.kwargs[name])
except (TypeError, LookupError):
return DefaultWrapper()
def __contains__(self, name):
return True
이제 표시된 모든 예제가 오류 없이 작동합니다.
text = "'{foo[a]}', '{foo[b]}'"
foo = {"a": "A"}
print(text.format_map(DefaultWrapper(foo=foo)))
# 'A', ''
text = "'{foo}', '{bar[index][i]}', '{foobar[a]}', '{foobar[b]}'"
print(text.format_map(DefaultWrapper(foo="Foo", foobar={"a": "A"})))
# 'FOO', '', 'A', ''
# the old way still works the same as before
from collections import defaultdict
text = "'{foo}', '{bar[index][i]}'"
print(text.format_map(defaultdict(DefaultWrapper, foo="FOO")))
# 'FOO', ''
이를 위한 방법은 다음과 같습니다.
import traceback
def grab_key_from_exc(exc):
last_line_idx = exc[:-1].rfind('\n')
last_line = exc[last_line_idx:]
quote_start = last_line.find("'")
quote_end = last_line.rfind("'")
key_name = last_line[quote_start+1:quote_end]
return key_name
def partial_format(input_string, **kwargs):
while True:
try:
return input_string.format(**kwargs)
except:
exc = traceback.format_exc()
key = grab_key_from_exc(exc)
kwargs[key] = '{'+key+'}'
def partial_format(string, **kwargs):
for k, v in kwargs.items():
string = string.replace('{'+k+'}', str(v))
return string
partial_format('{foo} {bar}', foo='FOO')
>>> 'FOO {bar}'
기본 인수를 사용하는 함수로 묶을 수 있습니다.
def print_foo_bar(foo='', bar=''):
s = '{foo} {bar}'
return s.format(foo=foo, bar=bar)
print_foo_bar(bar='BAR') # ' BAR'
언급URL : https://stackoverflow.com/questions/11283961/partial-string-formatting
'programing' 카테고리의 다른 글
R에서 "<-"(범위 지정)을 어떻게 사용합니까? (0) | 2023.07.19 |
---|---|
Python에서 두 목록이 순환적으로 동일한지 확인하는 방법 (0) | 2023.07.19 |
Python 3에서 수백만 개의 정규식 교체 속도 향상 (0) | 2023.07.19 |
Python 생성기 패턴에 해당하는 C++ (0) | 2023.07.19 |
그리드 보기 정렬:방향 정렬 항상 오름차순 (0) | 2023.07.19 |