title: How to remove a substring of characters from a PySpark Dataframe StringType() column, conditionally based on the length of strings in columns?
body: <p>I have a PySpark Dataframe with a StringType() column that has mostly 15 characters. However, some rows have 11 characters. Example:</p>
  
  <pre><code>df = 
  +--------------+--------+
  |             code|state|
  +--------------+--------+
  |'334445532234553'|wa   |
  |'332452132234553'|mn   |
  |'45532234553'    |fl   |
  |'679645532234553'|mo   |
  |'918535532234553'|ar   |
  |'174925532234553'|wi   |
  |'45532234553'    |al   |
  |'928405532234553'|ca   |
  +--------------+--------+
  </code></pre>
  
  <p>I need all rows to have 11 characters, with the last 4 characters removed from any row containing 15 characters. So this is my desired output:</p>
  
  <pre><code>df.show(8) = 
  +-------------+-----+
  |         code|state|
  +-------------+-----+
  |'33444553223'|wa   |
  |'33245213223'|mn   |
  |'45532234553'|fl   |
  |'67964553223'|mo   |
  |'91853553223'|ar   |
  |'17492553223'|wi   |
  |'45532234553'|al   |
  |'92840553223'|ca   |
  +-------------+-----+
  </code></pre>
  
  <p>So far I have this transformation, which removes that last 4 characters from ALL of the rows in my column called 'code':</p>
  
  <pre><code>from pyspark.sql.functions import substring, length, col, expr
  
  df = df.withColumn("code",expr("substring(code, 1, length(code)-4)"))
  </code></pre>
  
  <p>So I need to do something to make this conditional on the length of the string within the row.</p>
  
  <p><strong>EDIT</strong> With help from @gmds, I found this solution:</p>
  
  <pre><code>df.withColumn("code",expr("substring(code, 1, 11)"))
  </code></pre>