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>Use the given separator to cut off the head of each string.  Check first to make sure it has "Class", so we know the comma-space is there.</p>

<pre><code>med_school = ["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'",
              "text:'Class of 1989, Rush Medical School / Knox College'",
              "text:'Bernie\'s Back-Alley School of Black-Market Techniques'"
             ]

school_name = []
for first in med_school:
    name = first.value
    if ", " in name:
        cut  = name.index(", ")
        name = name[cut+2:]
    else:
        name = name[6:-1]
    school_name.append(name)

print school_name
</code></pre>

<p>output (with extra line feeds to improve readability):</p>

<pre><code>["University of Maryland School of Medicine'",
 "Johns Hopkins University School of Medicine'",
 "Raymond and Ruth Perelman School of Medicine at the University of Pennsylvania'"
 "Rush Medical School / Knox College'", 
 "Bernie's Back-Alley School of Black-Market Techniques"]
</code></pre>

<p>You could also wrap the loop into a list comprehension:</p>

<pre><code>school_name = [name.value[name.value.index(", ")+2:] \
                       if ", " in name \
                       else name[6:-1]   \
                   for name in med_school]
</code></pre>

python xlrd