简体   繁体   中英

Python quotation mark canceler algorithm

i = 1
def textconverter(t,color='black'):
    #Magically change all quotation marks (') to (\')
    cwprint(t,color)
def cwprint(t,color='black'):
    global i
    exec('label%d = Label(cw,text=\''%i+t+'\',fg=color).grid(row='+str(i)+')')
    i += 1
textconverter('test')

I am building a small chat program to experiment with the Tkinter and socket libraries, but however I ran into this problem: I want to print a value (text which is sent by the user) on the screen using a label.

Everything goes alright untill the user inputs a string including a quotation mark. For example: 'Don't do that'

Python will think that the string is 'Don' and doesn't recognise the 't do that' part. Is there any way to fix this?

Thanks

btw: cwprint stands for print on chat window

OK, we got here a XY-problem par excellence. Don't use exec to create sequential variable names. Use a list instead:

i = 1
def cwprint(t,labels,color='black'):
    global i
    text = '{} {}'.format(i, t)
    labels.append (Label(cw,text=text,fg=color).grid(row=i))
    i += 1

labels = []
cwprint ('Hello', labels)
cwprint ('World', labels)

No need for exec or for string escaping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM