首页 > 解决方案 > 如何在 Python 中使用 xlrd 从具有多个值的单个单元格中获取单独的值,以逗号分隔?

问题描述

因此,假设我在 excel 中有一个名为名称的列,然后在第一个单元格中它有“George,Bill,Sally”。我如何使用 xlrd 分离这些值并在 Python 中打印它们。

csv_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + 
"\FilePath\\"
file_location = csv_dir + "filename"
wb = xlrd.open_workbook(file_location)
sheet = wb.sheet_by_index(0)
for row in range(1, sheet.nrows):
    name = sheet.cell_value(row, 0)
    print(name)

所以现在我得到乔治、比尔、莎莉作为结果。我希望它打印为:

George 
Bill
Sally

每个名称一次打印一行。基本上我想打印出三个不同的字符串,每个字符串代表一个名称,而不是所有三个名称的一个字符串。

标签: pythonpython-3.xxlrd

解决方案


如果您只想打印出来,请使用str.replace()

for row in range(1, sheet.nrows):
    name = sheet.cell_value(row, 0)
    print(name.replace(',', '\n').replace(' ', ''))

如果您想实际将值放入列表中,请使用str.split()

for row in range(1, sheet.nrows):
    name = sheet.cell_value(row, 0)
    as_list = name.replace(' ', '').split(',')  # the replace is to remove any spaces
    print(*as_list, sep='\n')

推荐阅读