Reputation: 95
I have a file I'm parsing, on each line in the same column are one of the values; 0, 1 or -1. I want to parse this so that the numeric values are all in line as below. I am trying to this via an if statement with and/or operators. I cannot get my head around the and/or as when I test this with a print statement, output either prints 1's or prints 0's.
Desired output:
0
1
-1
if number.startswith('1' and '0'):
return number.append(' ')
print number
Upvotes: 0
Views: 76
Reputation: 1
Firstly, you're using .startswith with a coherent intention, but the arguments don't work that way, try this:
if number.startswith('1', '0'):
Secondly, .append does not do what you want. If you want to add a space in front of number if it begins with '1' or '0', try this:
if number.startswith('1', '0'):
number = ' ' + number
print number
Additionally, .append is used to add an item to the end of a list, for example:
>>> list = [1, 2]
>>> list.append('x')
>>> list
[1, 2, 'x']
Upvotes: 0
Reputation: 1124998
'1' and '0'
resolves to just '0'
:
>>> '1' and '0'
'0'
Boolean operators are not the same thing English grammatical constructs!
The str.startswith()
method takes a tuple of values to test for:
number.startswith(('1', '0'))
and it'll return True
if your string starts with '1'
or it starts with '0'
.
However, in this case you can just use string formatting to pad out your number:
return format(int(number), '-2d')
This pads your number out to a field two characters wide, leaving space for a negative sign:\
>>> format(-1, '-2d')
'-1'
>>> format(0, '-2d')
' 0'
>>> format(1, '-2d')
' 1'
Upvotes: 3
Reputation: 118021
The problem is that the expression '1' and '0'
is being evaluated as a bool
, and will evaluate to '0'
. The whole expression will then be if number.startswith('0'):
so the '1'
is never being checked.
You should to change this
if number.startswith('1' and '0'):
To
if number.startswith('1') or number.startswith('0'):
Or
if number[0] in ('1', '0'):
Upvotes: 0