formatting in python
# There are 3 different types of formatting. >>> name = "John" >>> age = 19 >>> language = "python" >>> print(f"{name} of age {age} programs in {language}") # Commonly used. John of age 19 programs in python >>> print("%s of age %d programs in %s" %(name, age, language)) # %s for str(), %d for int(), %f for float(). John of age 19 programs in python >>> print("{} of age {} programs in {}".format(name, age, language)) # Values inside .format() will be placed inside curly braces repectively when no index is specified. John of age 19 programs in python >>> print("{2} of age {1} programs in {0}".format(name, age, language)) # Index can be specified inside of curly braces to switch the values from .format(val1, val2, val3). python of age 19 programs in John
python format string
>>> nombre = 357568.12312 >>> nombre2 = 568.568768 >>> nombre3 = -34.3432 >>> nombre4 = 23 >>> print(f'{nombre : >+20_.4f} {nombre2 : >+20_.4f}') >>> print(f'{nombre3 : >+20_.4f} {nombre4 : >+20_.4f}') +357_568.1231 +568.5688 -34.3432 +23.0000
Source: he-arc.github.io
string format method python
# ------------------- string format, f-string ---------------------------- # {} is placeholder num1 = 5 num2 = 3 print(f'{num1} times {num2} is {num1 / num2:.2f}') #2f means print to 2 decimal precision #5 times 3 is 1.67 #explicit call format() method number1 = 'One' number2 = 'Two' number3 = 'Three' # default(implicit) order default_order = "{}, {} and {}".format(number1,number2,number3) print(default_order) # One, Two and Three # order using positional argument positional_order = "{1}, {0} and {2}".format(number1,number2,number3) print(positional_order) # Two, One and Three # order using keyword argument keyword_order = "{i}, {j} and {k}".format(j=number1,k=number2,i=number3) print(keyword_order) # Three, One and Two