title: Pandas re.compile function – IndexError: string index out of range
body: <p>This code for <code>pandas</code> searches for <code>r"\d+X|X\d+"</code> for each cell in a DataFrame column. 
  If it finds <code>"X"</code> it changes it into <code>"x"</code>.</p>
  
  <pre><code>match = re.compile(r"\d+X|X\d+", flags=re.IGNORECASE)
  
  def f(value):
      f2 = lambda x: match.findall(x)[0] if len(match.findall(x)) &gt; 0 else ""
  
      leverage = f2(value)
  
      if leverage[0].replace("X","x") == "x":
          leverage = "".join(leverage[1:])+leverage[0].replace("X","x")
  
      #Do other stuff here for var
      return var
  
  df["description"] = df["name"].map(lambda x:f(x))
  </code></pre>
  
  <hr>
  
  <p>Problem: If no <code>"x"</code> or <code>"X"</code> is found in the cell in column <code>"name"</code>, it gives the error: </p>
  
  <pre><code>if leverage[0].replace("X","x") == "x":
  IndexError: string index out of range
  </code></pre>
  
  <p>How can I circumvent this problem for strings that doesn't contain any of these characters?</p>
  
  <hr>
  
  <p>Example DataFrame:</p>
  
  <pre><code>import pandas as pd
  import re
  
  df = pd.DataFrame(["LONG APPLE X5 C", "SHORT APPLE C"], columns=["name"])
  </code></pre>