@@ -1236,17 +1236,36 @@ def visit_JoinedStr(self, node):
12361236
12371237 new_fstring_parts = []
12381238 quote_types = list (_ALL_QUOTES )
1239+ fallback_to_repr = False
12391240 for value , is_constant in fstring_parts :
12401241 if is_constant :
1241- value , quote_types = self ._str_literal_helper (
1242+ value , new_quote_types = self ._str_literal_helper (
12421243 value ,
12431244 quote_types = quote_types ,
12441245 escape_special_whitespace = True ,
12451246 )
1247+ if set (new_quote_types ).isdisjoint (quote_types ):
1248+ fallback_to_repr = True
1249+ break
1250+ quote_types = new_quote_types
12461251 elif "\n " in value :
12471252 quote_types = [q for q in quote_types if q in _MULTI_QUOTES ]
1253+ assert quote_types
12481254 new_fstring_parts .append (value )
12491255
1256+ if fallback_to_repr :
1257+ # If we weren't able to find a quote type that works for all parts
1258+ # of the JoinedStr, fallback to using repr and triple single quotes.
1259+ quote_types = ["'''" ]
1260+ new_fstring_parts .clear ()
1261+ for value , is_constant in fstring_parts :
1262+ if is_constant :
1263+ value = repr ('"' + value ) # force repr to use single quotes
1264+ expected_prefix = "'\" "
1265+ assert value .startswith (expected_prefix ), repr (value )
1266+ value = value [len (expected_prefix ):- 1 ]
1267+ new_fstring_parts .append (value )
1268+
12501269 value = "" .join (new_fstring_parts )
12511270 quote_type = quote_types [0 ]
12521271 self .write (f"{ quote_type } { value } { quote_type } " )
0 commit comments