"""
-import sys, encodings, encodings.aliases
+import sys
+import encodings
+import encodings.aliases
+import re
+import collections
from builtins import str as _builtin_str
import functools
amount -= 1
return s[lpos:rpos+1]
+_percent_re = re.compile(r'%(?:\((?P<key>.*?)\))?'
+ r'(?P<modifiers>[-#0-9 +*.hlL]*?)[eEfFgGdiouxXcrs%]')
+
def format(percent, value, grouping=False, monetary=False, *additional):
"""Returns the locale-aware substitution of a %? specifier
(percent).
additional is for format strings which contain one or more
'*' modifiers."""
# this is only for one-percent-specifier strings and this should be checked
- if percent[0] != '%':
- raise ValueError("format() must be given exactly one %char "
- "format specifier")
+ match = _percent_re.match(percent)
+ if not match or len(match.group())!= len(percent):
+ raise ValueError(("format() must be given exactly one %%char "
+ "format specifier, %s not valid") % repr(percent))
+ return _format(percent, value, grouping, monetary, *additional)
+
+def _format(percent, value, grouping=False, monetary=False, *additional):
if additional:
formatted = percent % ((value,) + additional)
else:
formatted = _strip_padding(formatted, seps)
return formatted
-import re, collections
-_percent_re = re.compile(r'%(?:\((?P<key>.*?)\))?'
- r'(?P<modifiers>[-#0-9 +*.hlL]*?)[eEfFgGdiouxXcrs%]')
-
def format_string(f, val, grouping=False):
"""Formats a string in the same way that the % formatting would use,
but takes the current locale into account.
(self.sep, self.sep))
+class TestFormatPatternArg(unittest.TestCase):
+ # Test handling of pattern argument of format
+
+ def test_onlyOnePattern(self):
+ # Issue 2522: accept exactly one % pattern, and no extra chars.
+ self.assertRaises(ValueError, locale.format, "%f\n", 'foo')
+ self.assertRaises(ValueError, locale.format, "%f\r", 'foo')
+ self.assertRaises(ValueError, locale.format, "%f\r\n", 'foo')
+ self.assertRaises(ValueError, locale.format, " %f", 'foo')
+ self.assertRaises(ValueError, locale.format, "%fg", 'foo')
+ self.assertRaises(ValueError, locale.format, "%^g", 'foo')
+
+
class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting):
# Test number formatting with a real English locale.
def test_main():
tests = [
TestMiscellaneous,
+ TestFormatPatternArg,
TestEnUSNumberFormatting,
TestCNumberFormatting,
TestFrFRNumberFormatting,