Search code examples
stringpython-3.xequals-operator

'and', 'or' for python unequal statement between strings


I am reading a text file using python. Each line will be read if the first character does not equal to # or @. The content of the text is pasted in the end.

This works:

if line[0] != '#' and line[0] != '@':
  value=float(line[3:8])

But this does not work:

if line[0] != ('#' and '@'):
  value=float(line[3:8])

ValueError: could not convert string to float: 'his f'

This also does not work:

if line[0] != ('#' or '@'):
  value=float(line[3:8])

ValueError: could not convert string to float: '  tit'

So why both or and and not work?

The content of the text file:

# This file was created Wed Feb 21 12:32:25 2018
# Created by:
#                  :-) GROMACS - gmx do_dssp, VERSION 5.1.1 (-:
# 
# Executable:   /shared/ucl/apps/gromacs/5.1.1/intel-2015-update2/bin//gmx
# Data prefix:  /shared/ucl/apps/gromacs/5.1.1/intel-2015-update2
# Command line:
#   gmx do_dssp -f md_0_1_noPBC.xtc -s md_0_1.tpr -ssdump ssdump.dat -map ss.map -o ss.xpm -sc scount.xvg -a area.xpm -ta totarea.xvg -aa averarea.xvg -tu ns
# gmx do_dssp is part of G R O M A C S:
#
# Gnomes, ROck Monsters And Chili Sauce
#
@    title "Secondary Structure"
@    xaxis  label "Time (ns)"
@    yaxis  label "Number of Residues"
@TYPE xy
@ subtitle "Structure = A-Helix + B-Sheet + B-Bridge + Turn"
@ view 0.15, 0.15, 0.75, 0.85
@ legend on
@ legend box on
@ legend loctype view
@ legend 0.78, 0.8
@ legend length 2
@ s0 legend "Structure"
@ s1 legend "Coil"
@ s2 legend "B-Sheet"
@ s3 legend "B-Bridge"
@ s4 legend "Bend"
@ s5 legend "Turn"
@ s6 legend "A-Helix"
@ s7 legend "3-Helix"
@ s8 legend "5-Helix"
       0   278   106   199    10    44    60     9    15     0
     0.1   267   118   203     7    52    47    10     6     0
     0.2   245   144   175     8    54    51    11     0     0
     0.3   264   118   192     8    58    56     8     3     0

Solution

  • line[0] not in ['#' , '@'] will do the trick.

    It checks if line[0] exists in a given array.