Quick questions about Python Dictionary

Asked 2 years ago, Updated 2 years ago, 73 views

This is part of the Aegis Publishing Algorithm book. I'm reviewing it again, but I don't understand it no matter how much I look at it. There are several questions in related communities, but no one has answered...

def card_conv(x: int, r: int) -> str:
    """Returns a string representing the number after converting an integer x to r"""

    d = '' # string after conversion
    dchar = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    n = len(str(x)) # Digits before conversion

    print(f'{r:2} | {x:{n}d}') # Dictionary?....
    while x > 0:
        print(' +' + (n + 2) * '-') # (to make the number of --- according to the number of digits when expressing the expression look neat)
        if x // r:
            print(f'{r:2} | {x // r:{n}d} … {x % r}')
        else:
            print(f'     {x // r:{n}d} … {x % r}')
        d+=dchar[x %r] #Take out the corresponding character and combine it
        x //= r

    returned[::-1] #Return in reverse order

medium the eighth row In print(f'{r:2} | {x:{n}d}), is it correct that {r:2} means {r:2} and set the value to 2? If so, I wonder which syntax you need this dictionary for I don't even know what d means in {x:{n}d}

python dictionary

2022-09-20 13:32

1 Answers

This is not a dictionary. It's a completely unrelated grammar.

Grammar related to string formatting called f-string.

f"{r:2}" means to create a string so that the value of the variable r is two spaces (2).

Search Python f-string to learn how to use it. It's very convenient, so take this opportunity to practice well.

https://docs.python.org/ko/3/reference/lexical_analysis.html#f-strings


2022-09-20 13:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.