In this tutorial, we will learn how to underline user input in Python efficiently. Underlining a user input can be helpful in various cases, such as differentiating the output from other lines of text or making the information more visually appealing. Let’s dive in and learn how to achieve this!
Step 1: Get User Input
First, we need to get the text input from the user using the Python built-in input() function. You can also include a prompt for the user, like so:
1 |
text_input = input("Enter the text you want to underline: ") |
Step 2: Calculate the Length of the Input Text
In order to underline the input text, we need to calculate its length. The length of the text will help us generate the underline characters based on the text provided. We can use the in-built len() function for this:
1 |
text_length = len(text_input) |
Step 3: Create the Underline
For underlining, you can use any character of your choice. In this tutorial, we will use the hyphen (-) character to create a visually appealing underline. We will multiply the character “-” by the length of the input text to create the underline string:
1 |
underline = '-' * text_length |
Step 4: Display the Result
Now that we have the user input and the underline, it is time to display the result. We can simply print the user input followed by the underline:
1 2 |
print(text_input) print(underline) |
Here’s the full code:
1 2 3 4 5 |
text_input = input("Enter the text you want to underline: ") text_length = len(text_input) underline = '-' * text_length print(text_input) print(underline) |
Now, let’s look at the output of the code:
Example Output:
Enter the text you want to underline: Hello, World! Hello, World! -------------
Conclusion
In this tutorial, we have learned how to underline user input in Python using a few simple steps. We obtained user input, calculated its length, created the underline string based on the length, and finally printed the result. This can be easily applied in various other situations where you want to stylize your text output in Python.