How to 'raw text' a variable in Python?

Pyderman picture Pyderman · Jul 12, 2015 · Viewed 9.9k times · Source

I am opening a workbook in openpyxl thus:

wb = load_workbook(r'seven.xlsx', data_only=True)

The name of the spreadsheet won't always be know in advance, so I need to rewrite this hardcoding to allow for a variable, while still maintaining the r?

If my variable name is sheet, then:

wb = load_workbook(sheet, data_only=True)

will omit the r.

And obviously I cannot do:

wb = load_workbook(r'sheet', data_only=True)

How do we achieve the prepending of r to a variable / how do we wrap a vriable within r''?

Answer

Doren picture Doren · Aug 16, 2018

I did not understand really what you were trying to do, but if you have a string and you want to create a raw text there are two main methods I know of:
raw_text = [str_text]
and
str_text = "%r"%str_text
raw_text = str_text[1:-1].