Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix rewrite of u strings to f strings #762

Merged
merged 1 commit into from Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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