-1

In Python i am creating a classmethod and i am using a classmethod to get my parameters from a string by spliting it i am getting what i want but cannot understand why i get a list when i am not using * and not getting list when using *. here's my code below.

 @classmethod
 def from_one_str(cls, onestr):
    print(*onestr.split(",")) # getting two string

 # on running this is result - John C++

    print(onestr.split(",")) # getting a list of two strings
 # on running this is result - ['John', 'C++']

 # This is what i am running - John = Programmer.from_one_str("John,C++")

1 Answers1

2

In a function call, the * operator unpacks the given list into separate arguments.

print(*["John", "C++"])

is thus equivalent to

print("John", "C++")

To bring this back to your code:

def from_one_str(onestr):
    print(*onestr.split(","))
  1. You call from_one_str() with the string "John,C++"
  2. The string will be split by "John,C++".split(",") into ["John", "C++"]
  3. That list will be then spread to arguments for print by the * operator.
  4. print prints each argument – "John" and "C++" – separated by space.
  5. You see John C++.
AKX
  • 152,115
  • 15
  • 115
  • 172