Wie kann man am einfachsten Prüfen, ob ein String als erstes Zeichen ein "#"- Zeichen hat ?!
mfg
donchris
Kommentare aus einem String entfernen.
-
- User
- Beiträge: 773
- Registriert: Mittwoch 5. November 2003, 18:06
- Wohnort: Schweiz
- Kontaktdaten:
Code: Alles auswählen
zeile[0] == '#'
RTFM
Code: Alles auswählen
'#comment'.startswith('#')
Das funktioniert leider nicht. Ich habe es so auch schon einmal probiert.
if line[0] == '#'
^
SyntaxError: invalid syntax
Und der 2. Vorschlag funktioniert auch nicht wirklich:
EDIT: funktioniert ! Danke derdon !
if line[0] == '#'
^
SyntaxError: invalid syntax
Und der 2. Vorschlag funktioniert auch nicht wirklich:
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()
EDIT: funktioniert ! Danke derdon !
Zuletzt geändert von donchris am Freitag 23. Januar 2009, 14:06, insgesamt 3-mal geändert.
Aus timeit_curses.py:
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
Zuletzt geändert von derdon am Freitag 23. Januar 2009, 14:05, insgesamt 1-mal geändert.
Code: Alles auswählen
line = "# test"
if line[0] == '#':
print "Kommentar"
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
Hello world!
Das ist trotzdem eine Lösung die nicht 100% geht, wenn man eine leere Zeichenkette bekommt, gibt's einen `IndexError`. `startswith()` kommt damit klar.