Python query for code examples

142 views Asked by At

I want to create something like a dictionary for python code examples. My problem is, that I have to escape all the code examples. Also r'some string' is not useful. Would you recommend to use an other solution to query this entries?

import easygui

lex = {"dict": "woerter = {\"house\" : \"Haus\"}\nwoerter[\"house\"]",\
   "for": "for x in range(0, 3):\n    print \"We are on time %d\" % (x)",\
   "while": "while expression:\n    statement(s)"}

input_ = easygui.enterbox("Python-lex","")
output = lex[input_]
b = easygui.textbox("","",output)
2

There are 2 answers

1
Martijn Pieters On BEST ANSWER

Use triple quoting:

    lex = {"dict": '''\
woerter = {"house" : "Haus"}
woerter["house"]
''',
           "for": '''\
for x in range(0, 3):
    print "We are on time %d" % (x)
''',
           "while": '''\
while expression:
    statement(s)
'''}

Triple-quoted strings (using ''' or """ delimiters) preserve newlines and any embedded single quotes do not need to be escaped.

The \ escape after the opening ''' triple quote escapes the newline at the start, making the value a little easier to read. The alternative would be to put the first line directly after the opening quotes.

You can make these raw as well; r'''\n''' would contain the literal characters \ and n, but literal newlines still remain literal newlines. Triple-quoting works with double-quote characters too: """This is a triple-quoted string too""". The only thing you'd have to escape is another triple quote in the same style; you only need to escape one quote character in that case:

triple_quote_with_embedded_triple = '''Triple quotes use \''' and """ delimiters'''
0
Xun Lee On

I guess you can use json.dumps(data, incident=1) to convert the data, and transfer into easygui.textbox. like this below:

import json
import easygui
resp = dict(...)
easygui.textbox(text=json.dumps(resp, indent=1))