Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'raw text' a variable in Python?

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''?

like image 373
Pyderman Avatar asked Jul 12 '15 06:07

Pyderman


People also ask

How do you set a raw string to a variable in Python?

Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.

What does \r do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

How do I print raw data in Python?

To create a raw string in Python, you place an r befor the beginning quotation mark of the string. A raw string completely ignores all escape characters. It prints the string exactly as entered.

How do you make a string literal in Python?

A string literal can be created by writing a text(a group of Characters ) surrounded by the single(”), double(“”), or triple quotes. By using triple quotes we can write multi-line strings or display in the desired way.


1 Answers

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].

like image 132
Doren Avatar answered Sep 28 '22 00:09

Doren