What does 'f' means before a string in Python?

前端 未结 3 845
时光说笑
时光说笑 2021-01-25 08:16

I\'m new here and also new to Python. I wonder what does f in print(f\'Column names are {\"-\".join(row)}\') do I tried deleting it and then \'Column n

相关标签:
3条回答
  • 2021-01-25 09:08

    This is called f-strings and are quite straightforward : when using an "f" in front of a string, all the variables inside curly brackets are read and replaced by there value. For example :

        age = 18
        message = f"You are {age} years old"
        print(message)
    

    Will return "You are 18 years old"

    This is similar to str.format (https://docs.python.org/3/library/stdtypes.html#str.format) but in a more concise way.

    0 讨论(0)
  • 2021-01-25 09:08

    String starting with f are formatted string litrals.

    Suppose you have a variable:

    pi = 3.14

    To catenate it to a string you'd do:

    s = "pi = " + str(pi)

    Formatted strings come in handy here. Using them you can use this do the same:

    s = f"pi = {pi}"

    {pi} is simply replaced by the value in the pi

    0 讨论(0)
  • 2021-01-25 09:17

    join method returns a string in which the elements of sequence have been joined by a separator. In your code, it takes row list and join then by separator -.

    Then by using f-string, expression specified by {} will be replaced with it's value.

    Suppose that row = ["1", "2", "3"] then output will be Column names are 1-2-3.

    0 讨论(0)
提交回复
热议问题