Anayatc
Anayatc

Reputation: 27

Index blank string python

The below functions works as I want but if the argument contains a blank string within the list it doesn't index as I hoped it would.

def number(lines):
    return ['{0}: '.format(lines.index(i) +1) + i for i in lines]



print(number(["a", "b", "c"]))

returns:

["1: a", "2: b", "3: c"]

exactly how I want it to return the list

however if the argument for the function contains a string that is blank for example:

print(number(["a", "", ""]))

returns:

["1: a", "2: ", "2: "]

Can someone explain why this happens, and how I can correct it to always count up from one regardless of a list element is blank

Upvotes: 2

Views: 1680

Answers (3)

TidB
TidB

Reputation: 1759

The index method gives you the first index where the space appears in the list. This isn't limited to just empty strings, but any character/string that appears twice in the list. Use enumerate to have a counting variable instead.

def number(lines):
    return ['{0}: {1}'.format(i+1, j) for i, j in enumerate(lines)]

Upvotes: 2

BPL
BPL

Reputation: 9863

Here's a possible working solution:

def number(lines):
    return ['{0}: {1}'.format(i + 1, l) for i, l in enumerate(lines) if l.strip() != ""]

Upvotes: 0

Jay Parikh
Jay Parikh

Reputation: 2489

if you dont want blank string then try

    return ['{0}: '.format(lines.index(i) +1) + i for i in lines if i!='']

Upvotes: 0

Related Questions