How to Print a Set without Brackets in Python?

Estimated read time 2 min read

To print a set without brackets in Python, you can use a loop to iterate through each element in the set and print each element using the print() function, separated by a space.

Here is an example:

my_set = {1, 2, 3, 4, 5}

for element in my_set:
    print(element, end=" ")

In this example, we have a set called my_set with five integer elements. We use a for loop to iterate through each element in the set, and then print each element using the print() function. We use the end parameter to separate the elements with a space instead of a newline character.

The output of this code will be:

1 2 3 4 5

Note that the order of the elements in the output may not match the order in which they were added to the set, because sets are unordered collections. If you want to remove any leading or trailing spaces from the output, you can use the strip() method to remove them before printing the output, like this:

my_set = {1, 2, 3, 4, 5}

output_string = ""
for element in my_set:
    output_string += str(element) + " "

print(output_string.strip())

In this example, we create an empty string called output_string and use a for loop to iterate through each element in the set. We append each element to the string, followed by a space character. Finally, we use the strip() method to remove any leading or trailing spaces from the output string before printing it.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply