String formatting in Python

后端 未结 12 2006
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:14

I want to do something like String.Format(\"[{0}, {1}, {2}]\", 1, 2, 3) which returns:

[1, 2, 3]

How do I do this in Python?

相关标签:
12条回答
  • 2020-11-22 08:36

    To print elements sequentially use {} without specifying the index

    print('[{},{},{}]'.format(1,2,3))
    

    (works since python 2.7 and python 3.1)

    0 讨论(0)
  • 2020-11-22 08:36

    PEP 498 which landed in python 3.6 added literal string interpolation, which is basically a shortened form of format.

    You can now do:

    f"[{1}, {2}, {3}]"
    

    Common other uses I find useful are:

    pi = 3.141592653589793
    today = datetime(year=2018, month=2, day=3)
    
    num_2 = 2     # Drop assigned values in
    num_3 = "3"   # Call repr(), or it's shortened form !r
    padding = 5   # Control prefix padding
    precision = 3 #   and precision for printing
    
    
    f"""[{1},
         {num_2},
         {num_3!r},
         {pi:{padding}.{precision}},
         {today:%B %d, %Y}]"""
    

    Which will produce:

    "[1,\n     2,\n     '3',\n      3.14,\n     February 03, 2018]"
    
    0 讨论(0)
  • 2020-11-22 08:37

    Before answering this question please go through couple of articles given below:

    Python Official Docs here

    Useful article:

    • Python String format() - here

    Now let's answer this question

    Question: I want to do something like:

    String.Format("[{0}, {1}, {2}]", 1, 2, 3) which returns:

    [1, 2, 3]

    How do I do this in Python?

    Answer:

    Well this is certainly a one-line code answer which is

    print("[{0},{1},{2}]".format(1, 2, 3))

    When you execute this one-line code a list containing three values as [1, 2, 3] will be printed. I hope this was pretty simple and self-explanatory.

    Thanks

    Tanu

    0 讨论(0)
  • 2020-11-22 08:38

    You have lot of solutions :)

    simple way (C-style):

    print("[%i, %i, %i]" %(1, 2, 3))
    

    Use str.format()

    print("[{0}, {1}, {2}]", 1, 2, 3)
    

    Use str.Template()

    s = Template('[$a, $b, $c]')
    print(s.substitute(a = 1, b = 2, c = 3))
    

    You can read PEP 3101 -- Advanced String Formatting

    0 讨论(0)
  • 2020-11-22 08:42

    If you don't know how many items are in list, this aproach is the most universal

    >>> '[{0}]'.format(', '.join([str(i) for i in [1,2,3]]))
    
    '[1, 2, 3]'
    

    It is mouch simplier for list of strings

    >>> '[{0}]'.format(', '.join(['a','b','c']))
    '[a, b, c]'
    
    0 讨论(0)
  • 2020-11-22 08:43

    Very short answer.

    example: print("{:05.2f}".format(2.5163)) returns 02.51

    • {} Set here Variable
    • : Start Styling
    • 0 leading with zeroes, " " leading with whitespaces
    • 5 LENGTH OF FULL STRING (Point counts, 00.00 is len 5 not 4)
    • .2 two digit after point, with rounding.
    • f for floats
    0 讨论(0)
提交回复
热议问题