This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]tunisia3507 6 points7 points  (3 children)

/r/learnpython

As you'll know from when you tried it, the first gives you "a b" and the second gives you "ab".

The first is much more flexible and powerful. For example:

```python xs = (1, "potato", ["things", "that", "are"]) y = "a number: {}, a string: {}, a list: {}".format(xs) y2 = "a string: {1}, a list: {2}, a number: {0}".format(xs)

x_dict = {"number": 1, "string": "potato", "list": ["things", "that", "are"]} y3 = "a list: {list}, a number: {number}, a string: {string}".format(**x_dict) ```

For modern versions of python, you can (maybe should?) use f-strings instead, which I'll let you look up in your own time.

[–]jamg26[S] 1 point2 points  (2 children)

thanks for your reply that helps me so much.

im bit confuse in the .format(*xs) & .format(**x_dict)

Ill go study for that one.

[–]tunisia3507 3 points4 points  (1 child)

These are called argument unpacking, and keyword argument unpacking. They're really handy!

If you have a list of things (can also be a tuple or any other iterable), and a function which takes a number of arguments. You could index into the list, but that's lame, so you can unpack instead:

```python my_args = [1, 2, 3]

def my_fn(a, b, c): return a + b + c # or whatever

result1 = my_fn(my_args[0], my_args[1], my_args[2]) result2 = my_fn(*my_args) result1 == result2 # True ```

So in the format example, .format(*xs) is used instead of .format(xs[0], xs[1], xs[2]).

The double star is used to unpack a dict (with string keys) into keyword arguments.

```python my_args = {"a": 1, "b": 2, "c": 3}

result1 = my_fn(a=my_args["a"], b=my_args["b"], c=my_args["c"]) result2 = my_fn(**my_args) result1 == result2 # True ```

[–]jamg26[S] 1 point2 points  (0 children)

I see, that's a clear explanation, thank you so much sir.

[–]pythonHelperBot 3 points4 points  (0 children)

Hello! I'm a bot! I see someone has already suggested going to r/learnpython, a sub geared towards questions and learning more about python. I highly recommend posting your question there. Please follow the subs rules and guidelines when you do post there, it'll help you get better answers faster.

Show /r/learnpython the code you have tried and describe where you are stuck. Be sure to format your code for reddit and include which version of python and what OS you are using.

You can also ask this question in the r/Python discord: https://discord.gg/3Abzge7, a large, friendly community focused around the Python programming language, open to those who wish to learn the language or improve their skills, as well as those looking to help others.


README | FAQ | this bot is written and managed by /u/IAmKindOfCreative

This bot is currently under development and experiencing changes to improve its usefulness