Home > other >  Adding user generated input into HTML file on python
Adding user generated input into HTML file on python

Time:10-16

I am taking a beginning python class. Here is the question:

"Write a program that asks the user for his or her name, then asks the user to enter a sentence that describes himself or herself. Here is an example of the program’s screen:

Enter your name: Julie Taylor Enter

Describe yourself: I am a computer science major, a member of the Jazz club, and I hope to work as a mobile app developer after I graduate. Enter

Once the user has entered the requested input, the program should create an HTML file, containing the input, for a simple Web page."

This is the code I have so far.

# Collect user data.
name = input("Enter your name: ")
content = input("Describe yourself: ")

# Create a file object.
f = open("program6.html", "w")


# Adding input data to the HTML file
f.write("<html>\n<head>\n<title> \nOutput Data in an HTML file \
        </title>\n</head> <body><h1>name</h1>\
        \n<h2>content</h2> \n</body></html>")

# Create a string to store the html script.
data = '''
<html>
<head>
</head>
<body>
   <center>
      <h1>name</h1>
   </center>
   <hr />
   {content}
   <hr />
</body>
</html>'''

            
# Saving the data into the HTML file
f.close()

I am struggling because when it creates the webpage, it inputs the words "name" and "content" versus utilizing the user input. How can I insert the users responses?

Thanks!

CodePudding user response:

place name and content in curly brackets and then use .format() or a leading f to format your string.

f.write(f"<html>\n<head>\n<title> \nOutput Data in an HTML file \
        </title>\n</head> <body><h1>{name}</h1>\
        \n<h2>{content}</h2> \n</body></html>")

CodePudding user response:

You can use f-strings. Do this by putting an f before the opening quotes. Here is your code with the applied changes.

# Collect user data.
name = input("Enter your name: ")
content = input("Describe yourself: ")

# Create a file object.
f = open("program6.html", "w")


# Adding input data to the HTML file
f.write(f"<html>\n<head>\n<title> \nOutput Data in an HTML file \
        </title>\n</head> <body><h1>{name}</h1>\
        \n<h2>{content}</h2> \n</body></html>")

# Create a string to store the html script.
data = f'''
<html>
<head>
</head>
<body>
   <center>
      <h1>{name}</h1>
   </center>
   <hr />
   {content}
   <hr />
</body>
</html>'''

            
# Saving the data into the HTML file
f.close()

CodePudding user response:

Another alternate to bitflip's answer using the % operator:

# Adding input data to the HTML file
f.write("<html>\n<head>\n<title> \nOutput Data in an HTML file \
        </title>\n</head> <body><h1>%s</h1>\
        \n<h2>%s</h2> \n</body></html>" %(name, content))
  • Related