title: How can I replace a substring in a Python pathlib.Path?
body: <p>Is there an easy way to replace a substring within a <code>pathlib.Path</code> object in Python? The <a href="https://realpython.com/python-pathlib/" rel="noreferrer">pathlib module is nicer in many ways</a> than storing a path as a <code>str</code> and using <code>os.path</code>, <code>glob.glob</code> etc, which are built in to <code>pathlib</code>. But I often use files that follow a pattern, and often replace substrings in a path to access other files:</p>
  
  <pre><code>data/demo_img.png
  data/demo_img_processed.png
  data/demo_spreadsheet.csv
  </code></pre>
  
  <p>Previously I could do:</p>
  
  <pre><code>img_file_path = "data/demo_img.png"
  proc_img_file_path = img_file_path.replace("_img.png", "_img_proc.png")
  data_file_path = img_file_path.replace("_img.png", "_spreadsheet.csv")
  </code></pre>
  
  <p><code>pathlib</code> can replace the file extension with the <code>with_suffix()</code> method, but only accepts extensions as valid suffixes. The workarounds are:</p>
  
  <pre><code>import pathlib
  import os
  
  
  img_file_path = pathlib.Path("data/demo_img.png")
  proc_img_file_path = pathlib.Path(str(img_file_path).replace("_img.png", "_img_proc.png"))
  # os.fspath() is available in Python 3.6+ and is apparently safer than str()
  data_file_path = pathlib.Path(os.fspath(img_file_path).replace("_img.png", "_img_proc.png"))
  </code></pre>
  
  <p>Converting to a string to do the replacement and reconverting to a <code>Path</code> object seems laborious. Assume that I never have a copy of the string form of <code>img_file_path</code>, and have to convert the type as needed.</p>