Kommentare aus einem String entfernen.
Verfasst: Freitag 23. Januar 2009, 13:56
Wie kann man am einfachsten Prüfen, ob ein String als erstes Zeichen ein "#"- Zeichen hat ?!
mfg
donchris
mfg
donchris
Seit 2002 Diskussionen rund um die Programmiersprache Python
https://www.python-forum.de/
Code: Alles auswählen
zeile[0] == '#'
Code: Alles auswählen
'#comment'.startswith('#')
Code: Alles auswählen
fobj = open("C:/httpd.conf","r")
settings = {}
for line in fobj:
if line.startswith('#'):
continue
zuordnung = line.split(" ")
settings[zuordnung[0]] = zuordnung[1]
fobj.close()
Code: Alles auswählen
In [20]: from __future__ import with_statement
In [21]: with open('timeit_curses.py') as f:
for line in f:
if line.lstrip().startswith('#'):
print line,
....:
....:
#!/usr/bin/env python
# initializing curses
# make the cursor invisible
# a counter to track the number of pressing <SPACE>
# wait for a keypress
# if <SPACE> is pressed...
# print the start time if <SPACE> was pressed the 1st time
# show end time and difference
# format the output
# delete the calculated data and start again
# delete start time
# delete end time
# delete difference time
# reset the counter and restart
# quit the app if `q` is pressed
Code: Alles auswählen
line = "# test"
if line[0] == '#':
print "Kommentar"
Was funktioniert denn nicht?donchris hat geschrieben:Und der 2. Vorschlag funktioniert auch nicht wirklich:
Der SyntaxError resultiert aus dem fehlenden Doppelpunkt. Der Bedingung ist korrekt...donchris hat geschrieben:Das funktioniert leider nicht. Ich habe es so auch schon einmal probiert.
if line[0] == '#'
^
SyntaxError: invalid syntax