Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
f-strings and backslashes
#1
Hi!

If I run this:

string5 = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
string6 = '\n'

print(f"Applying string5.split('a') to 'string5' results in: {string5.split('a')}")
it works and produces this output:
Output:
Applying string5.split('a') to 'string5' results in: ['De', 'r Alice,\nHow h', 've you been? I ', 'm fine.\nThere is ', ' cont', 'iner in the fridge\nth', 't is l', 'beled "Milk Experiment".\nPle', 'se do not drink it.\nSincerely,\nBob']
But it seems that f-strings and backslashes don't like each other, so:

string5 = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
string6 = '\n'

print(f"Applying string5.split('\n') to 'string5' results in: {string5.split('\n')}")
produces the following:
Error:
SyntaxError: f-string expression part cannot include a backslash.
I read somewhere that creating a string with the value of '\n' was a trick to avoid that error. So I tried:
string5 = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
string6 = '\n'

print(f"Applying string5.split({string6}) to 'string5' results in: {string5.split({string6})}")
but it doesn't do the trick and it shows the following error message:
Error:
Traceback (most recent call last): File "C:/Users/User1/AppData/Local/Programs/Python/Python37/atbs_06_checkingStrings_04.py", line 10, in <module> print(f"Applying string5.split({string6}) to 'string5' results in: {string5.split({string6})}") TypeError: must be str or None, not set
So now I have 2 doubts:
1) How to separate the multiline string by the new line escape ('\n')?
2) Why the error does say 'must be str or None, not set'? (Supposedly string6 is a string (string6 = '\n') and not a set).

Thank you and all the best,
newbieAuggie2019

"That's been one of my mantras - focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains."
Steve Jobs
Reply
#2
i guess you want
print(f"Applying string5.split({repr(string6)}) to 'string5' results in: {string5.split(string6)}")
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Oct-24-2019, 06:56 PM)buran Wrote: i guess you want
print(f"Applying string5.split({repr(string6)}) to 'string5' results in: {string5.split(string6)}")

Thank you!

It works, although I don't fully understand the repr() function. It seems to be related somehow to str() and even ... to magic!!! Rolleyes

I tried to see the difference with this:

string7 = 'Paris is the capital of France.'

print(f"This is with str(): {str(string7)}")
print(f"This is with str(): {str(5.0/2.0)}")
print(f"This is with repr(): {repr(string7)}")
print(f"This is with repr(): {repr(5.0/2.0)}")
producing this output:
Output:
This is with str(): Paris is the capital of France. This is with str(): 2.5 This is with repr(): 'Paris is the capital of France.' This is with repr(): 2.5
where it seems to me that the only difference is that the repr() function puts the string between quotes.

I checked also the built-in help, which I don't usually do, as it seems like Chinese to me:
Output:
>>> help(repr) Help on built-in function repr in module builtins: repr(obj, /) Return the canonical string representation of the object. For many object types, including most builtins, eval(repr(obj)) == obj.
so I guess that's also why I don't fully understand it ... it returns the canonical string representation of the object ... and I'm just a layman ... Big Grin

I see that you simplified also some part of my code, eliminating problems that I usually have. My code:

print(f"Applying string5.split({string6}) to 'string5' results in: {string5.split({string6})}")
Your code:

print(f"Applying string5.split({repr(string6)}) to 'string5' results in: {string5.split(string6)}")
where {string5.split({string6})} has been simplified to {string5.split(string6)}. I tend to substitute things between curly braces "{}", but it seems that when it is a substitution inside another substitution, my curly braces produce an error or something not working properly. It looks like that when it is a substitution inside another substitution, I have to eliminate the curly braces from the inner substitution. Is that right?

Thanks and all the best,
newbieAuggie2019

"That's been one of my mantras - focus and simplicity. Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains."
Steve Jobs
Reply
#4
you need to use repr() because otherwise the new line \n will be "translated" in actual new line in the output (i.e. the output will be split on 2 lines)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Why not using the method splitlines?
print(f"Applying string5.splitlines to 'string5' results in: {string5.splitlines()}")
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
(Oct-26-2019, 06:07 AM)DeaD_EyE Wrote: Why not using the method splitlines?
my understanding was they OP wants flexibility - split at arbitrary char, not just line ends. Otherwise first part of the output doesn't make sense to use f-string to output what split char is, it could be hardcoded
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand strings and lists of strings Konstantin23 2 761 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Very simple question about filenames and backslashes! garynewport 4 1,932 Jan-17-2023, 05:02 AM
Last Post: deanhystad
  Splitting strings in list of strings jesse68 3 1,766 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Parsing JSON with backslashes bazcurtis 3 9,328 Feb-08-2020, 01:13 PM
Last Post: bazcurtis
  Finding multiple strings between the two same strings Slither 1 2,519 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  lists, strings, and byte strings Skaperen 2 4,225 Mar-02-2018, 02:12 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020