PsiElement (@NotNull PyStringLiteralExpression oldExpression, @NotNull String prefix, @NotNull String suffix, @NotNull String newText) { // 'foobar' -> '%sbar' % s final PyElementGenerator generator = PyElementGenerator.getInstance(oldExpression.getProject()); final LanguageLevel languageLevel = LanguageLevel.forElement(oldExpression); final PsiElement parent = oldExpression.getParent(); final boolean parensNeeded = parent instanceof PyExpression && !(parent instanceof PyParenthesizedExpression); final StringBuilder builder = new StringBuilder(); if (parensNeeded) { builder.append("("); } builder.append(prefix); builder.append("%s"); builder.append(suffix); builder.append(" % "); final int pos = builder.toString().length(); builder.append(newText); if (parensNeeded) { builder.append(")"); } final PyExpression expression = generator.createExpressionFromText(languageLevel, builder.toString()); final PsiElement newElement = oldExpression.replace(expression); return newElement.findElementAt(pos); }