Home > Software engineering >  How to include keywords within fstring in python3
How to include keywords within fstring in python3

Time:10-26

I am new to python and fstring, Can you please help me how to write multiple lines to the file with fstring, it is to create a config file with all the contents within the fstring is to be written to a file, ignoring the content what it has

    def create_testfile(self) -> None:
        """writes the config file 
       """
    value = f""" #==================================
## NAT network DHCP params configuration
bridge=$(ifconfig | grep  "flags" | awk -F : '{print $1}' | sed '/lo/d' | sed '/vif/d')
echo "${command}"
case "${command}" in
    online)
...
...
...
        port_num_check
esac
"""
    with open("network.txt", "w") as network:
        network.write(value)

Gives an error message File "", line 1 (print $1) ^ SyntaxError: invalid syntax

I tried changing the triple quoted string to single quoted string but there is another problem with that, adding \n will result in error message. SyntaxError: f-string expression part cannot include a backslash

CodePudding user response:

You are using f-strings where they are not necessary. You just need a multiline string. The error you are getting is because of how f-strings work.

everything inside curly braces { and } is being treated as a variable in python instead of what you want it to be treated as, just a plain string.

one of the solutions is to just not use f-strings like I said earlier.

other solution is to escape the curly braces so they are not used as an escape sequence for variables. you can do that by surrounding existing {...} with a pair of braces, again. so {...} should be written as {{...}}.

do this where ever you want the commands in the shell script are meant to be treated as variables in the shell script but not in python.

to be precise modify your program as follows

def create_testfile(self) -> None:
        """writes the config file 
       """
    value = f""" #==================================
## NAT network DHCP params configuration
bridge=$(ifconfig | grep  "flags" | awk -F : '{{print $1}}' | sed '/lo/d' | sed '/vif/d')
echo "${{command}}"
case "${{command}}" in
    online)
...
...
...
        port_num_check
esac
"""
    with open("network.txt", "w") as network:
        network.write(value)

notice how in your question the syntax highlighting is treating the text inside braces as variables but in the code above it is being treated just as strings.

some things to read for f-strings:

  1. Real Python's Article
  2. PEP 498 -- Literal String Interpolation

CodePudding user response:

You cannot have a $ sign in your f-string expression. I think in this case it would be best if you did this line by line and then joined them together using "\n".join(lines)

if you really want to make everything in one string then you can use a backslash () to ignore the characters.

  • Related