PYTHON查找每行倒数第二个非空单元格
时间: 2023-12-22 17:52:31 浏览: 39
要查找每行的倒数第二个非空单元格,可以使用Python中的split()方法将单元格分割为一个列表,然后从列表中倒数第二个元素开始向前遍历,直到找到非空元素为止。以下是一个示例代码:
```python
def find_second_last_cell(row):
cells = row.split(',')
for i in range(len(cells)-2, -1, -1):
if cells[i].strip() != '':
return cells[i].strip()
return None
# 测试代码
row1 = 'apple, banana, orange, pear, ,'
row2 = 'red, green, blue, , ,'
print(find_second_last_cell(row1)) # 输出 'pear'
print(find_second_last_cell(row2)) # 输出 'blue'
```
相关问题
python 提取字符串倒数第二行的文本
要提取字符串的倒数第二行文本,你可以使用以下方法:
```python
def extract_second_last_line(text):
= text.split('\n')
if len(lines) >= 2:
return lines[-2]
else:
return None
text = '''
Hello
This is the first line.
This is the second line.
This is the third line.
'''
second_last_line = extract_second_last_line(text)
print(second_last_line)
```
在这个例子中,我们首先将字符串按行分割成一个列表,然后通过索引 `-2` 来获取倒数第二行的文本。
python读取列表倒数第二个元素
要读取列表的倒数第二个元素,可以使用负数索引。在Python中,索引从0开始,-1表示最后一个元素,-2表示倒数第二个元素。下面是一个示例:
```python
my_list = [1, 2, 3, 4, 5]
second_last_element = my_list[-2]
print(second_last_element)
```
输出结果为:4