-1
from email import message

def main(): # Creates a main function to initiate the program
    global name, info
    
    name = input("Enter your name: ") # Makes inputs that requires an user to enter info
    info = input("Describe yourself: ")
    
main() # The program starts here

f = open('test3.html','w')

message = """<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""

f.write(message)
f.close()

Hello, I am creating a py file that accepts the user's inputs (which are {name} and {info} in my code) and creates a .html file. I tried to use + name + or + info + but both not worked. Are there any other ways that I can use to make it work correctly? Thank you so much for reading my question

whoami
  • 27
  • 4
  • Does this answer your question? [Is there a Python equivalent to Ruby's string interpolation?](https://stackoverflow.com/questions/4450592/is-there-a-python-equivalent-to-rubys-string-interpolation) – Pranav Hosangadi Jun 10 '22 at 01:59

1 Answers1

1

Use an f string

from email import message

def main(): # Creates a main function to initiate the program
    global name, info
    
    name = input("Enter your name: ") # Makes inputs that requires an user to enter info
    info = input("Describe yourself: ")
    
main() # The program starts here

f = open('test3.html','w')

# add 'f' before the first quotation mark
message = f"""<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""

f.write(message)
f.close()

You probably also want to refactor your code to look like this:

from email import message

def main(): # Creates a main function to initiate the program
  name = input("Enter your name: ") # Makes inputs that requires an user to enter info
  info = input("Describe yourself: ")

  with open('test3.html', 'w') as f:
    body = f"""<html>
<head>
</head>
<body>
<center>
<h1>{name}</h1>
</center>
<hr />
{info}
<hr />
</body>
</html>"""
    f.write(body)

if __name__ == "__main__":
  main()

In the original, you imported message, but then overrode that import by assigning a variable with that same name, so this new version fixes that (though message is now an unused import, unless this isn't the entire code file)

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • The file writing should probably also be in main, and opening the file should use `with`. But yep, f-strings. – AKX Jun 10 '22 at 01:37