简体   繁体   English

用单引号和双引号创建一个字符串

[英]Create a string with single and double quotes

I need to insert a formula into Excel using Python.我需要使用 Python 在 Excel 中插入一个公式。 I am creating a dataframe and adding a column containing the formulas and then writing it into an Excel.我正在创建一个数据框并添加一个包含公式的列,然后将其写入 Excel。

The formula has the format '=HYPERLINK("#'"&F2&"'!A1",F2)'公式的格式为'=HYPERLINK("#'"&F2&"'!A1",F2)'

F2 is a variable and all other characters are constant. F2 是一个变量,所有其他字符都是常量。 I need to dynamically generate this string.我需要动态生成这个字符串。

I tried doing =HYPERLINK("#'"&F2&"'!A1",F2) but it is not working and I got '=HYPERLINK("#\\'"&F2&"\\'!A1",F2)' which includes the back slash and the formula does not work.我尝试做=HYPERLINK("#'"&F2&"'!A1",F2)但它不起作用,我得到了'=HYPERLINK("#\\'"&F2&"\\'!A1",F2)' ,其中包括反斜杠,公式不起作用。

How do I create a string like '=HYPERLINK("#'"&F2&"'!A1",F2)' ?如何创建像'=HYPERLINK("#'"&F2&"'!A1",F2)'这样的字符串?

Any help would be highly appreciated.任何帮助将不胜感激。

参考The method you used works with Python 3, i checked it with trinket.io您使用的方法适用于 Python 3,我使用 trinket.io 进行了检查

Since you are making string dynamically.由于您正在动态制作字符串。 There are two things you can do.你可以做两件事。

  1. r'=HYPERLINK("#'"&F2&"'!A1",F2)' r signifies raw string (if you are not using any variable). r'=HYPERLINK("#'"&F2&"'!A1",F2)' r 表示原始字符串(如果您没有使用任何变量)。

  2. If you are making string dynamically using other variables.如果您使用其他变量动态创建字符串。 Use formatted string.使用格式化字符串。

    var1= '"#'"&F2&"'!A1"' var2= 'F2' formula= f'=HYPERLINK({var1},{var2} )'

print(formula)

'=HYPERLINK("#&F2&!A1",F2 )'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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