I am doing an if in which I type 2 alphabets separated by commas and join them, for this I am doing the following:
if op1 == str(2):
c1 = set(input('Ingrese el alfabeto 1 separado por comas: '))
c2 = set(input('Ingrese el alfabeto 2 separado por comas: '))
print(f'A U B: {c1 | c2}')
It unites them without problem but when printing the response by entering values for c1 = 'a,b,c' y c2 = 'd,e,f'
I get the following:
A U B: {'e', 'f', ',', 'b', 'c', 'd', 'a'}
Why does it show me messy and because in a position I get ','
that I could be failing? Thank you
The simple answer is that you need to use a method called
split()
. But let's go with the explanation.Set
A set, as you have already been told, is an unordered data set without repetition that can contain any immutable data type, a
set
is also a mutable data type (unlikefrozenset
) but it does not allow the assignment of values ( item assignment) and you can't access its indices either by bracket notation (object[index]
so it's not a subscriptable object) but it can be traversed and we can also add and remove items.Problem
When doing
input('Ingrese el alfabeto 1 separado por comas: ')
this you are simply asking for the values, if for example I enterHolas, que hay
the result of the function itinput
will beHolas, que hay
and if we convert it to a set it will give us your result, if you want to separate the values by commas and obtain those separated values, use the methodsplit()
and as argument is passed the character by which the separation will be made.And we do:
As we can see, we no longer take the comma and we could convert that list to and we
set
would obtain{'c','a','b'}
(the same but disordered). Your code should go like this:Observation
Now I will take a hypothetical scenario, where instead of entering letters separated by commas we enter words separated by commas. In this case it would no longer work as we thought.
If we run and test we will get:
Here a
set
but is created according to the words that we enter, this is because when doing the separation we would be left with this:['Holas','que','hay']
and we would not have each letter separated, what we would have to do would be to eliminate the comma and make a set of the entire string complete.We can do that or just ask to enter the values but not separated by commas :)
Note
For the ordering of
set
there is no solution, the data will always be out of order, if you want to have them ordered you can use lists but of course you could no longer do set operations as you do with aset
.In a quick search I came across this result . First paragraph:
The
set
then is messy by definition.As for the comma, it's one of the characters you entered, why wouldn't it be? From the same tutorial: