Skip to content

Commit

Permalink
Merge pull request #762 from asottile/f-strings-no-u-prefix
Browse files Browse the repository at this point in the history
fix rewrite of u strings to f strings
  • Loading branch information
asottile committed Nov 29, 2022
2 parents a389e99 + 43293bb commit c1c97ba
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
8 changes: 7 additions & 1 deletion pyupgrade/_plugins/fstrings.py
Expand Up @@ -4,6 +4,7 @@
from typing import Iterable

from tokenize_rt import Offset
from tokenize_rt import parse_string_literal
from tokenize_rt import Token
from tokenize_rt import tokens_to_src

Expand Down Expand Up @@ -43,7 +44,12 @@ def _to_fstring(

parts = []
i = 0
for s, name, spec, conv in parse_format('f' + src):

# need to remove `u` prefix so it isn't invalid syntax
prefix, rest = parse_string_literal(src)
new_src = 'f' + prefix.translate({ord('u'): None, ord('U'): None}) + rest

for s, name, spec, conv in parse_format(new_src):
if name is not None:
k, dot, rest = name.partition('.')
name = ''.join((params[k or str(i)], dot, rest))
Expand Down
5 changes: 5 additions & 0 deletions tests/features/fstrings_test.py
Expand Up @@ -64,6 +64,11 @@ def test_fix_fstrings_noop(s):
r'f"\N{snowman} {a}"',
id='named escape sequences',
),
pytest.param(
'u"foo{}".format(1)',
'f"foo{1}"',
id='u-prefixed format',
),
),
)
def test_fix_fstrings(s, expected):
Expand Down

0 comments on commit c1c97ba

Please sign in to comment.