Python - Print list without brackets
Python - Print list without brackets
To print list without square brackets in Python, i.e., opening square bracket at the starting and closing square bracket at the ending, you can get the string representation of the list, and then strip the square brackets from the string representation of the list.
For example, consider the following list.
x = ['apple', 'banana', 100, 200]
When you print this list to output, you would get the following output.
['apple', 'banana', 100, 200]
When we say that we want to print the list without brackets, we want the following to be printed to the console output.
'apple', 'banana', 100, 200
Just the square brackets to be removed from the edges. Rest all same.
Steps to print list without brackets in Python
- Given a list in x.
- Pass x as argument to str() built-in function, and convert the list into a string. Store the returned string in x_str.
x_str = str(x)
- Strip the square brackets from the starting and ending of the string x_str using string strip() method, and store the returned string back into the variable x_str.
x_str = x_str.strip("[]")
- Print this string value in result to standard output.
Program
The complete program to print the given list without brackets to standard output is given below.
Python Program
# Given list
x = ['apple', 'banana', 100, 200]
# Convert list to string
x_str = str(x)
# Strip brackets
x_str = x_str.strip("[]")
print(x_str)
Output
'apple', 'banana', 100, 200
There you have it. The list has been printed to output without brackets.
Make the code concise
You can write the last three steps in a single statement, if you want, as shown in the following program.
Python Program
# Given list
x_str = ['apple', 'banana', 100, 200]
# Print list without brackets
print(str(x_str).strip("[]"))
Output
'apple', 'banana', 100, 200
Separate function to print list without brackets
You can create a function print_list_without_brackets() and make the code reusable.
Python Program
# Custom function to print list without brackets
def print_list_without_brackets(x):
x_str = str(x)
print(x_str.strip("[]"))
# Given list
x = ['apple', 'banana', 100, 200]
print_list_without_brackets(x)
Output
'apple', 'banana', 100, 200
Summary
In this tutorial, we have seen how to print a given list without brackets to standard output using str() built-in function and string strip() method.