I'm using App Engine's webapp. This request handler outputs a form with a text field. On submission, it will get the text and add <h1>
tags to lines that start with #
. I used repr()
to be able to split the text into a list of lines, and eval()
to analyze the text from each line without the u'
at the start of the string that comes from repr()
.
class Test(webapp.RequestHandler):
def get(self):
self.response.out.write('<form method=\'post\' action=\'\'>')
self.response.out.write('<textarea name=\'text\'></textarea>')
self.response.out.write('<input type=\'submit\' value=\'Submit\'/>')
self.response.out.write('</form>')
def post(self):
output = []
for line in repr(self.request.get('text')).split('\\n'):
if eval(line)[0] == '#':
output.append('<h1>'+line+'</h1>')
else:
output.append(line)
self.response.out.write('\\n'.join(output))
The way the code is now, its giving me this error:
File "<string>", line 1
u'#somestring\r
开发者_如何学C ^
SyntaxError: EOL while scanning string literal
If I use just line[0]
instead of eval(line)[0]
, everything works fine except that it doesn't work for the first line. Even if the first line starts with #
, the conditional will go for the else
because the first characters will be u'
and not #
. Trying to work around that with eval()
is giving me that error. How can I work around this problem?
To split the text, the strings have a built in splitlines
method:
for line in self.request.get('text').splitlines():
... do whatever ...
Then to see if a particular line begins with a #
, try this:
if line.strip()[0]=='#':
... do whatever ...
Put together:
for line in self.request.get('text').splitlines():
if line.strip()[0] == '#':
... do whatever ...
精彩评论