![](/img/trans.png)
[英]How to get values with in a single string in a list without getting separated by commas in csv file using python?
[英]How do I get separate values from a single cell with multiple values in it separated by commas using xlrd in Python?
因此,假設我在excel中有一列稱為“名稱”,然后在第一個單元格中包含“喬治,比爾,薩利”。 我將如何使用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
每個名稱一次打印一行。 基本上,我想打印出三個不同的字符串,每個字符串代表一個名稱,而不是所有三個名稱的一個字符串。
如果只想打印出來,請使用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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.