Jun 24, 2020

String Formatting by format() method

String formatting by format() method(Basics)

Hello guys, we here are about to discuss about format() method of formatting a string.

We’ve actually seen what exactly format() can do.

The syntax is,

Box is a mixture of format codes and placeholders for the arguments.

And, here a0,a1,..... are positional arguments and b1, b2, ..... are keyword arguments with some specific values.

What is positional and keyword parameters?

Positional parameters: parameters that can be accessed with index of parameter inside curly braces.

Keyword parameters: parameters of type key=value, that can be accessed with key of parameter inside curly braces.

Example,


Argument 0 and argument 1, here, are “SAHIL” and the floating number “4.5285” respectively.

Now,

·       The 0th argument doesn’t have any other format codes, so it doesn’t perform any other operation.

·       The 1st argument is 4.5285, but as you see it has other format code in the bsox string. Therefore other operation may follow as given.

·       1:5.2f. Here 5 means the minimum width/padding the number can take. Here it is allocated 5 places including “.”.

·       f specifies the format is dealing with a float number. If not correctly specified, it will give out an error.

·       The (2) part tell us to round off the number after 2 places. Therefore, 45285 turns into 4.53

Basic formatting with format()


Number formatting types

Number Formatting Types

Type

Meaning

d

Decimal integer

c

Corresponding Unicode character

b

Binary format

o

Octal format

x

Hexadecimal format

X

Hexadecimal format

n

Same as 'd'. Except it uses current locale setting for number separator

e

Exponential notation.

E

Exponential notation

f

Displays fixed point number (Default: 6)

g

General format. Rounds number to p significant digits. (Default precision: 6)

G

Same as 'g'. Except switches to 'E' if the number is large.

%

Percentage. Multiples by 100 and puts % at the end.

 

Try out these for better hold on it.

Number formatting with alignment

Number formatting with alignment

Type

Meaning

< 

Left aligned to the remaining space

^

Center aligned to the remaining space

> 

Right aligned to the remaining space

=

Forces the signed (+) (-) to the leftmost position

Example,


Same can be done with strings.

Advance string formatting

You are done with the basics.

Hello Python people, for this blog we have taken help from the book Python : The Complete Reference.


Hope all your doubts regarding this are clear now.

If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via instagram "@coding.winds".


Do subscribe to our daily blog update by clicking here.


Thank You!


No comments:

Post a Comment