mirror of
https://github.com/morpheus65535/bazarr
synced 2024-12-29 02:55:52 +00:00
44 lines
1 KiB
Python
44 lines
1 KiB
Python
def str_format(s, *args, **kwargs):
|
|
"""Return a formatted version of S, using substitutions from args and kwargs.
|
|
|
|
(Roughly matches the functionality of str.format but ensures compatibility with Python 2.5)
|
|
"""
|
|
|
|
args = list(args)
|
|
|
|
x = 0
|
|
while x < len(s):
|
|
# Skip non-start token characters
|
|
if s[x] != '{':
|
|
x += 1
|
|
continue
|
|
|
|
end_pos = s.find('}', x)
|
|
|
|
# If end character can't be found, move to next character
|
|
if end_pos == -1:
|
|
x += 1
|
|
continue
|
|
|
|
name = s[x + 1:end_pos]
|
|
|
|
# Ensure token name is alpha numeric
|
|
if not name.isalnum():
|
|
x += 1
|
|
continue
|
|
|
|
# Try find value for token
|
|
value = args.pop(0) if args else kwargs.get(name)
|
|
|
|
if value:
|
|
value = str(value)
|
|
|
|
# Replace token with value
|
|
s = s[:x] + value + s[end_pos + 1:]
|
|
|
|
# Update current position
|
|
x = x + len(value) - 1
|
|
|
|
x += 1
|
|
|
|
return s
|