Add curly brackets to python please
Curly bracket in this code (beginner)
How to use brackets in Python? - Post.Byes - Bytes
How to put brackets in a list accordingly in Python 3? - Stack Overflow
Videos
I'm confused about the use of the curly brackets in this code from a textbook. I thought the curly brackets are to call dictionaries. but first and last are not, am I right?
def get_formatted_name(first,last):
full_name=f"{first}{last}"
return full_name.title()
Here is an approach that uses an iterator for a change.
list_1 = [1,2,2]
list_2 = [1,2,3,4,5]
it = iter(list_2)
res = []
for take in list_1:
res.append([next(it) for _ in range(take)])
print(res) # -> [[1], [2, 3], [4, 5]]
Of course, a list-comprehension version of that exists as well1:.
it = iter(list_2)
res = [[next(it) for _ in range(take)] for take in list_1]
Finally, as @Chris_Rands notes in the comments below, you can use islice from the extremely useful itertools module. It takes care of the iterator-creating part of the code above and is this thus more compact.
import itertools
res = [list(itertools.islice(list_2, take)) for take in list_1]
print(res) # -> [[1], [2, 3], [4, 5]]
==========================================================================
1 Just remember to re-create the iterator!
This is one approach.
list_1 = [1,2,2]
list_2 = [1,2,3,4,5]
c = 0
res = []
for i in list_1:
res.append( list_2[c:c+i] )
c += i
print(res)
Output:
[[1], [2, 3], [4, 5]]
I am refreshing python skills after some time, I am getting confused when to use diff types of brackets, round, curly, or square
Any advice or tips on how to memorize or understand this?
Thanks
You need to double the {{ and }}:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
Here's the relevant part of the Python documentation for format string syntax:
Format strings contain “replacement fields” surrounded by curly braces
{}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{and}}.
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double {{ or }}
n = 42
print(f" {{Hello}} {n} ")
produces the desired
{Hello} 42
If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
produces
{hello}