1

I have four different variables, say,

s1 = 'Foo'
s2 = 'Boo'
s3 = 'Foo'
s4 = 'Duh'

Now, I would like to form a string of every unique value from all of s1, s2, s3 and s4 keeping the order. Like in the above case the string would be something like:

"We have a collection of types 'Foo', 'Boo' and 'Duh'."

Is there a simple way to achieve this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
skrowten_hermit
  • 437
  • 3
  • 11
  • 28
  • 2
    Something like: `set([s1,s2,s3,s4])` ? – Avihoo Mamka Aug 18 '16 at 06:43
  • If sequence doesn't matter, Mamka's solution should work well. – YiFei Aug 18 '16 at 06:44
  • @YiFei How can we modify Mamka's solution if sequence does matter? – skrowten_hermit Aug 18 '16 at 08:31
  • Set itself won't preserve any order, so you have to use a list. Wiktor has already posted an answer. If you have really a large number of variable, you can utilize python's *built-in* reflective programming and maintain both a list and set to ensure the performance, if needed. And if you want to preserve the order, you should specify it in your post, then it won't be marked as duplicate. Maybe it's still duplicate, I'm not sure :) – YiFei Aug 18 '16 at 08:57

1 Answers1

3

To get rid of duplicates and preserve the order of occurrence, you need to append values "manually":

s = "We have a collection of types {}."
lst = [s1,s2,s3,s4]
fin = []
for x in lst:
    if x not in fin:
        fin.append(x)
print(s.format(", ".join(fin)))

See this Python demo

If you were not going to preserve the order, you might use set that would return unique items in a list (just create a list from your variables):

s1 = 'Foo'
s2 = 'Boo'
s3 = 'Foo'
s4 = 'Duh'
print("We have a collection of types {}.".format(", ".join(set([s1,s2,s3,s4]))))

where:

  • "We have a collection of types {}.".format() is the string format method where the string literal contains a {} that is a placeholder for the only argument passed to the format method
  • ", ".join() - a method to make a string out of a list joining the items with a comma+space
  • set() - a method that takes an iterable and returns a frozenset, unique items in the iterable
  • [s1,s2,s3,s4] - a list created from the standalone vars

See Python demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563