How to 'raw text' a variable in Python?
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]
.
Pyderman
Some day, I'll be one of the ones answering questions. Until then, I endeavour to submit articulate, well thought-out questions. If you find issue with any of my questions, please add a comment stating why (rather than simply downvoting). That way, I and other submitters can improve.
Updated on July 26, 2022Comments
-
Pyderman almost 2 years
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''
? -
Pyderman almost 9 yearsI invite you to then to try
openpyxl.save()
on a Windows machine for a file name (such as in the example above) that does not contain backslashes, and omittingr''
. -
200_success almost 9 yearsWhat is the specific error that you have encountered? Please revise the question to provide complete background information about what you have tried and what failed.
-
Pyderman almost 9 yearsI don't think the example in question adds any context (it's openpyxl.loadworkbook(), but really it could be anything where a raw string is required but I want to pass a variable. Here it is anyway: stackoverflow.com/questions/31362887/…
-
SiHa almost 9 yearsWhere in the docs does it say you have to use that? I have used openpyxl in the past (I prefer xlsxwriter now) and did not have to use raw string literals anywhere. Yes, on Windows.
-
200_success almost 9 yearsYou must have misdiagnosed the problem.
r'all_done.xlsx'
is exactly the same as'all_done.xlsx'
, since there are no backslashes inside the string literal. If it's unable to write the file, then the cause must be something else. If I had to speculate, maybe the "invalid mode" part is relevant — perhaps you don't have write permission to the current directory? -
Pyderman almost 9 years@SiHa The docs don't say I have to use
r''
. Experience on Windows shows that I do. -
200_success almost 9 yearsExperience is no substitute for reasoning. The
r
prefix just makes it so that you can writer'C:\some\path\to\an.xlsx'
, which is less cumbersome than the equivalent'C:\\some\\path\\to\\an.xlsx'
. -
user8491363 about 4 yearsThis worked and just saved my night. But could you explain how it works? I've never seen a string operation like that. I'm on Python 3.7 so maybe it's from the older Python?