Python is a powerful yet easy-to-learn programming language that allows us to perform various tasks with concise code. In this blog post, we’ll discuss how to write a 30-line Python program that outputs personal information in a custom format: [title]标题 [换行] [content]内容 [换行] [tags]标签
.
Here’s an example of a Python program that collects personal information from the user and then prints it in the desired format:
python# Collect personal information from the user
name = input("Enter your name: ")
age = input("Enter your age: ")
occupation = input("Enter your occupation: ")
hobbies = input("Enter your hobbies (separated by commas): ")
# Split the hobbies by comma and remove any whitespace
hobbies = [hobby.strip() for hobby in hobbies.split(',')]
# Define the title, content, and tags for the output
title = "Personal Information"
content = f"Name: {name}\nAge: {age}\nOccupation: {occupation}\nHobbies: {', '.join(hobbies)}"
tags = "python, personal, information"
# Generate the final output string
output = f"[title]{title} [换行] [content]{content} [换行] [tags]{tags}"
# Print the output
print(output.replace('[换行]', '\n').replace('[title]', 'Title: ').replace('[content]', 'Content: ').replace('[tags]', 'Tags: '))
In this program, we first prompt the user to enter their name, age, occupation, and hobbies. The hobbies are separated by commas, and we use a list comprehension to split them and remove any leading or trailing whitespace.
Next, we define the title, content, and tags for the output. The content is a formatted string that includes the user’s personal information. The hobbies are joined with commas and spaces using the join()
method.
We then generate the final output string by combining the title, content, and tags in the desired format. Note that we use placeholders ([title]
, [content]
, [tags]
, and [换行]
) and replace them with their corresponding values and newline characters.
Finally, we print the output to the console. By using the replace()
method, we ensure that the placeholders are replaced with their intended values.
This program demonstrates the flexibility of Python’s string formatting and its ability to handle user input. With just 30 lines of code, we can create a useful program that collects and outputs personal information in a custom format.