Skip to content

Commit

Permalink
fix rewrite of u strings to f strings
Browse files Browse the repository at this point in the history
  • Loading branch information
asottile committed Nov 29, 2022
1 parent a389e99 commit 43293bb
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 43293bb

Please sign in to comment.