Python中创建多行连续超链接及解决位置实参报错问题
Hey there! Let's fix your issue and get those hyperlink lists working correctly in Python.
First, let's tackle that positional argument follows keyword argument error you're seeing. This happens when you mix positional arguments (like passing a string directly without a name) and keyword arguments (like heading="...") in the format() method, with positional ones coming after keyword ones. In your code snippet, it looks like you might have cut off the format() call, but we can restructure things entirely to avoid this problem.
Creating a Line-by-Line Hyperlink List
To make a clean, line-separated hyperlink list in your HTML output, use HTML's <ul> (unordered list) and <li> (list item) tags. Here's a step-by-step implementation:
- Define your HTML template with clear keyword placeholders (this makes your code way easier to maintain):
page_template = """ {page_heading} {intro_text} {extra_content_1} {extra_content_2} <!-- Hyperlink List --> <ul> {hyperlink_list} </ul> """
- Build your hyperlinks as HTML list items, then join them with newlines to get clean line breaks:
# Create each link as an <li> element links = [ '<li><a href="fatalities_per_year.html">A Look at Death Rate Over Time</a></li>', '<li><a href="fatalities_by_state.html">Fatalities Breakdown by Australian State</a></li>', '<li><a href="safety_trends.html">Road Safety Trend Analysis</a></li>' ] # Combine links into a single string with line breaks formatted_links = '\n'.join(links)
- Populate the template and write to your file (using a
withstatement is safer—it automatically closes the file for you):
with open("index.html", "w") as out_file: out_file.write(page_template.format( page_heading="<h1>Road Fatalities in Australia</h1>", intro_text="<p>On this site you will find road fatality statistical data.</p>", extra_content_1="<p>... key insights into fatality causes ...</p>", extra_content_2="<p>... regional comparisons and safety recommendations ...</p>", hyperlink_list=formatted_links ))
Why This Fixes Your Error
By using only keyword arguments in the format() call, you eliminate the positional/keyword argument conflict entirely. Every placeholder in your template maps directly to a named parameter, so there's no confusion about which value goes where.
If you ever need to use both positional and keyword arguments in the future, remember: positional arguments must come first, followed by keyword ones. But for templates like this, sticking to keyword arguments is always the cleaner approach.
内容的提问来源于stack exchange,提问作者Lee Mapstone

