1

I want to add some text to a file name before the extension. Example: name.ext >>> name_su.ext.
I can do it with traditional python string formatting:

filename = 'name.ext'
suffix = '_su'
print("{0}{2}{1}".format(*os.path.splitext(filename) + (suffix, )))
# This will print: name_su.ext

I wonder if I can achieve the same with f-string notation, in a single line, without calling os.path.splitext(filename) twice.

Marcos
  • 695
  • 9
  • 22

1 Answers1

0

Calling os.path.splitext() twice might be avoidable, but it's fast and readable:

print(f'{os.path.splitext(filename)[0] + suffix + os.path.splitext(filename)[1]}')
AlexM
  • 1,020
  • 2
  • 17
  • 35
  • Thank you, @AlexM. I was looking for a way to do it without calling twice `os.path.splitext()`. – Marcos Jun 21 '20 at 19:16
  • Why even bother with an f-string? `print(os.path.splitext(filename)[0] + suffix + os.path.splitext(filename)[1])` – wjandrea Jun 22 '20 at 15:10
  • Also, there's no need to call it twice, like I commented on the question: `suffix.join(os.path.splitext(filename))`. So if you needed an f-string, `print(f'{suffix.join(os.path.splitext(filename))}')` – wjandrea Jun 22 '20 at 15:15