Python - 如何将双引号附加到字符串并存储为新字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45208090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:49:45  来源:igfitidea点击:

Python - How to append double quotes to a string and store as new string?

pythonstringdouble-quotes

提问by activelearner

I am using Python 2.6+ and would like to append double quotes to a string and store it as a new string variable. I do not want to print it but use it later in my python script.

我正在使用 Python 2.6+ 并希望将双引号附加到字符串并将其存储为新的字符串变量。我不想打印它,但稍后在我的 python 脚本中使用它。

For example:

例如:

a = 'apple'
b = some_function(a) --> b would be equal to '"apple"'

How can I do this? All the solutions that I have looked at so far only work when printing the string.

我怎样才能做到这一点?到目前为止,我所看到的所有解决方案都只在打印字符串时有效。

回答by Maybe

Beautiful usage in python

python中的美丽用法

b = '"{}"'.format(a)

in python 3.6 (or above)

在 python 3.6(或更高版本)中

b = f'"{a}"'

work same!

工作一样!

回答by perigon

b = '"' + a + '"'

Notice that I am enclosing the double quotes in single quotes - both are valid in Python.

请注意,我将双引号括在单引号中——两者在 Python 中都是有效的。

回答by Md. Rezwanul Haque

You can try this way :

你可以试试这种方式:

def some_function(a):
    b = '"' + a + '"'
    return b

if __name__ == '__main__':
    a = 'apple'
    b = some_function(a)
    print(b)

Output:

输出:

"apple"

回答by hadi

def add_quote(a):
    return '"{0}"'.format(a)

and call it:

并称之为:

a = 'apple'
b = add_quote(a) # output => '"apple"'

回答by vinod

# adding double quotes to string
text = 'cool'
text = repr(text)
print(text)
"'cool'"

# python3