Python: Remove a portion of a string from a list of strings
<p>I used xlrd to extract a column from an excel sheet to make into a list.</p>

<pre><code>from xlrd import open_workbook
book = xlrd.open_workbook("HEENT.xlsx").sheet_by_index(0)
med_name = []
for row in sheet.col(2):
    med_name.append(row)
med_school = []
for row in sheet.col(3):
    med_school.append(row)
print(med_school)
</code></pre>

<p>Below is a snippet of the list: med_school.</p>

<pre><code>[text:'University of San Francisco', 
text: 'Harvard University', 
text:'Class of 2016, University of Maryland School of Medicine', 
text:'Class of 2015, Johns Hopkins University School of Medicine', 
text:'Class of 2014, Raymond and Ruth Perelman School of Medicine at the
University of Pennsylvania']
</code></pre>

<p>I want to remove "text:'Class of 2014" from each string in the list. I tried list comprehension, but I got an attribute error: 'Cell' object has no attribute 'strip'. Does anyone know of a way to create a list of medical school names that have just the medical school names without the class year and the word "text"?</p>

<p>The <code>xlrd</code> does not return you strings, it returns you instances of a class called <code>Cell</code>.  This has a property <code>value</code> that contains the string you are seeing.  </p>

<p>To modify these simply:</p>

<pre><code>for cell in med_school:
    cell.value = cell.value[:15]
</code></pre>

<p>This will remove the first 15 characters ("Class of 2014, ").  Alternatively you could use other approaches like string splitting (on ",") or a regex.</p>

<p>The point here is that you shouldn't be working directly on the values in the <code>med_schools</code> list, but on their <code>.value</code> property. Or extract it to somewhere else you could work on it.</p>

<p>For example, to get all of the text properties, dropping the prefix:</p>

<pre><code>values = [cell.value[15:] for cell in med_schools]
</code></pre>

<p>Or using a regex to replace to replace only those actualling containing the offending data</p>

<pre><code>values = [re.sub(r"^Class of \d{4}, ", "", cell.value) for cell in med_schools]
</code></pre>

python xlrd