Python3自动将单引号替换为

2024-04-29 09:39:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个python3软件,使用google\u语音和操作系统命令。你知道吗

一切工作正常,但当用户输入一个字符串与'字符我有这个错误:语法错误:未终止引用字符串

这是我的密码:

def textToSpeak():
global fieldValues

msg = "Enter the text to speak\n\nDon't use" +str(" \' ")+str(" write it like this : je tinvite chez moi, not je t\'invite chez moi ")
title = "Enter the text to speak"
fieldNames = ["Text to speak"]
fieldValues = []
fieldValues = multenterbox(msg, title, fieldNames)
speak()

def speak():
global lang, fieldValues
textValue = "google_speech -l" +str(lang) +str(" \'\"")+str(fieldValues[0])+str("\"\'")
os.system(textValue)

Tags: theto字符串textdefgooglemsgglobal
3条回答

似乎您正试图逃避用户输入的字符串。你知道吗

您可以使用repr()json.dumps()。你知道吗

>>> repr("je t'invite")
'"je t\'invite"'

>>> json.dumps("je t'invite")
'"je t\'invite"'

我终于找到了一个很好的答案:

textValue = "google_speech -l" +str(lang) +str(" \"")+str(fieldValues[0].replace("'","\'"))+str("\"")
os.system(textValue)

如果你坚持os.system,你想要^{}

Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list.

也就是说,我强烈建议移到the ^{} modulesubprocess.call将是这里os.system的最简单替代,尽管还有其他选项),并以列表形式传递参数,允许subprocess进行转义(在Windows上必要时),消除手动添加引号的需要,避免完全在Windows上进行字符串处理其他操作系统(它可以直接exec参数向量,不需要转义)。你知道吗

相关问题 更多 >