question related to formatting . Usage of format() in python - python

could anyone explain how format() works in python? where to use it, and how to use it?. I am not getting even I about this keyword

You can regarding it as a kind of string replacement.
{} part in the string -> string.format() content
Definition: https://www.w3schools.com/python/ref_string_format.asp
A pratical example can be like this:
base_url = 'www.xxxx.com/test?page={}'
for i in range(10):
url = base_url.format(i)
do sth

The format() method formats the specified value(s) and insert them inside the string's placeholder.
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
Here fname will be replaced by John and age will be replaced by 36, if you print txt1.
Alternatively you can use f strings .
eg:
fname= "John"
age= 36
print(f"My name is {fname}, I'm {age}")
Even it will print the same output.

Format is often applied as a str-type method: txt.format(...), where type(txt)='str'.
This function is used to insert values inside string's placeholders. Placeholders are curly brackets {} placed inside a string and the format() method returns a formatted string with the values plugged into the string.
This function also enables formatting different type of variables in different ways. E.g. float with value 0.0001 can be represented in floating point representation: 0.0001 or scientific representation 1e-4 using different specifires.
Usage:
txt = "My name is {name}. I'm {age} years old."
print(txt.format(name="Dan", age=32))
Will output: 'My name is Dan. I'm 32 years old.'
You can use positional arguments as well:
txt = "My name is {}. I'm {} years old."
print(txt.format("Dan", 32))
Where the values are taken by their order.
This will output the same result.
To format with different formatting you can use specifiers:
txt = "Decimal numbers: {number:d}"
print(txt.format(number=8340))
txt = "Fix point numbers: {number:.2f}"
print(txt.format(number=3.1415))
There are other specifiers that have other formatting behavior like centering some value to match some desired width:
txt = "{center:^20}"
print(txt.format(center='center'))
This will output ' center ' which contains exactly 20 characters.
There are many more formatting options that you can browse here
or in many other rescorces.

Related

How to replace multiple files with scraped html whilst numbered [duplicate]

Is it possible to use variables in the format specifier in the format()-function in Python? I have the following code, and I need VAR to equal field_size:
def pretty_printer(*numbers):
str_list = [str(num).lstrip('0') for num in numbers]
field_size = max([len(string) for string in str_list])
i = 1
for num in numbers:
print("Number", i, ":", format(num, 'VAR.2f')) # VAR needs to equal field_size
You can use the str.format() method, which lets you interpolate other variables for things like the width:
'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)
Each {} is a placeholder, filling in named values from the keyword arguments (you can use numbered positional arguments too). The part after the optional : gives the format (the second argument to the format() function, basically), and you can use more {} placeholders there to fill in parameters.
Using numbered positions would look like this:
'Number {0}: {1:{2}.2f}'.format(i, num, field_size)
but you could also mix the two or pick different names:
'Number {0}: {1:{width}.2f}'.format(i, num, width=field_size)
If you omit the numbers and names, the fields are automatically numbered, so the following is equivalent to the preceding format:
'Number {}: {:{width}.2f}'.format(i, num, width=field_size)
Note that the whole string is a template, so things like the Number string and the colon are part of the template here.
You need to take into account that the field size includes the decimal point, however; you may need to adjust your size to add those 3 extra characters.
Demo:
>>> i = 3
>>> num = 25
>>> field_size = 7
>>> 'Number {i}: {num:{field_size}.2f}'.format(i=i, num=num, field_size=field_size)
'Number 3: 25.00'
Last but not least, of Python 3.6 and up, you can put the variables directly into the string literal by using a formatted string literal:
f'Number {i}: {num:{field_size}.2f}'
The advantage of using a regular string template and str.format() is that you can swap out the template, the advantage of f-strings is that makes for very readable and compact string formatting inline in the string value syntax itself.
I prefer this (new 3.6) style:
name = 'Eugene'
f'Hello, {name}!'
or a multi-line string:
f'''
Hello,
{name}!!!
{a_number_to_format:.1f}
'''
which is really handy.
I find the old style formatting sometimes hard to read. Even concatenation could be more readable. See an example:
'{} {} {} {} which one is which??? {} {} {}'.format('1', '2', '3', '4', '5', '6', '7')
I used just assigned the VAR value to field_size and change the print statement. It works.
def pretty_printer(*numbers):
str_list = [str(num).lstrip('0') for num in numbers]
field_size = max([len(string) for string in str_list])
VAR=field_size
i = 1
for num in numbers:
print("Number", i, ":", format(num, f'{VAR}.2f'))

Remove space in print command for some specific values

n=str(input("Enter your name"))
a=str(input("Where do you live?"))
print("Hello",n,"How is the weather at",a,"?")
How to Remove space between {a & ?} in the print statement?
An f-string will give you better control over the exact formatting:
print(f"Hello {n}. How is the weather at {a}?")
Commas in python add a space in the output.
No need to use str as inputs in python are already treated as strings.
You can use this:
n = input("Enter your name")
a = input("Where do you live?")
print("Hello",n,"How is the weather at",a+"?")
This concatenates the two strings.
OR
n = input("Enter your name")
a = input("Where do you live?")
print(f"Hello {n}! How is the weather at {a}?")
This is called f-strings. It formats the string so you can put the value of a variable in the output.
You can simply do it by using end inside the print
by default its value is \n and if you set it an empty string ''
it won't add anything(or any space).
after printing a and the ? will print exactly after that.
so you can write the code below:
print("Hello",n,"How is the weather at",a, end='')
print("?")

How to use .format with a variable rather than text in python

I'm trying to replace a couple of placeholders in a string variable using .format(arg1,arg2) in the same way that I could with defining literal text to .format although I'm clearly taking the wrong approach as .format does not see the placeholders.
In a literal way I might do
var = """ this is a
{0} {1} """.format(colour, animal)
which would work just fine.
I have now moved that templated text into a text file, that I have read in, but want to substitute the args at run time.
What is the best way to achieve that please?
format is a method of a string object and will work just as well with a string held in a variable as with a hard-coded string constant.
So you can have for example:
template.txt
this is a
{0} {1}
and use this to read it and substitute the values:
with open("template.txt") as f:
template = f.read().strip()
colour = "red"
animal = "lion"
print(template.format(colour, animal))
Gives:
this is a
red lion
You can also use keywords to substitute, which would give you more flexibility about the ordering of the colour and the animal (or indeed, for the same token to appear multiple times or not at all).
Here is a template:
template.txt
This is a {colour} {animal}
Substitute using keywords:
with open("template.txt") as f:
template = f.read().strip()
colour = "red"
animal = "lion"
print(template.format(colour=colour, animal=animal))
gives:
This is a red lion
But now, as an example, here is an template which would be suitable for the Welsh language, where the order would be swapped round:
template.txt
{animal} {colour} ydy hon
Now substitute similarly:
print(template.format(colour="goch", animal="draig"))
draig goch ydy hon
It didn't matter that your format call had the items in the other order in the code, because they were matched up with the relevant keywords.
Again, this is no different from what you can do with hard-coded string constants.
var = """this is a {0} {1} """
print(var.format("red", "dog"))
with open("test.txt") as f:
var = f.read().format(colour, animal)

How to format a string in python to use a list

I have the following piece of code:
import textwrap
text_string = "This is a long string that goes beyond 40 characters"
wrapper = textwrap.TextWrapper(width=40)
word_list = wrapper.wrap(text=text_string)
year = '2018'
pkg = 'textwrap'
new_string = """This is a new string formatted in {1} with {2} resulting in
{3}""".format(year, pkg, *word_list)
If I were to run this piece of code here is what I observed:
{3} is replaced with the first element of word_list. Since I don't know the size of word_list I wanted {3} to take each member of the list on to a new line. and string new line should be:
""" This is a new string formatted in 2018 with textwrap resulting in
This is a long string that goes beyond 4
0 characters"""
but instead it becomes
""" This is a new string formatted in 2018 with textwrap resulting in
This is a long string that goes beyond 4
I couldn't determine how I could use format to accomplish this. I am not trying to print this and I dont want to insert '\n' because this new string gets appened to a file and not goign to be printed.
Thanks for your help.
You can call join on the list to turn it into a string comprised of all the elements in the list separated by a delimiter:
new_string = """This is a new string formatted in {1} with {2} resulting in
{3}""".format(year, pkg, " ".join(word_list))
If I understand what you are asking, then two ways to do what you want are:
1. Continue to use the wrap call to return a list
So we still are using the wrap method to return a list, in this case we will just have to build a string in the format as passing *args to format (called unpacking) requires a known length. Such:
import textwrap
text_string = "This is a long string that goes beyond 40 characters"
wrapper = textwrap.TextWrapper(width=40)
word_list = wrapper.wrap(text=text_string)
year = '2018'
pkg = 'textwrap'
new_string = """This is a new string formatted in {} with {} resulting in""".format(year,pkg)
new_string += str("\n{}" * len(word_list)).format(*word_list)
#originally had above using join but this method can increase performance if text is large
#join version: new_string = """This is a new string formatted in {} with {} resulting in \n{}""".format(year,pkg,"\n".join(word_list))
print(new_string)
I created the base string (new_string) then concated that with a new string (\n{}) which I multiplied as many times as there were elements in the list word_list - creating the needed number of {}s in the string for format with an unpacked word_list.
2. Use the "fill" method to just build a wrapped string
Note: here I use a dictionary as I personally think this is cleaner when passing values to format but you can change that back if not needed.
import textwrap
text_string = "This is a long string that goes beyond 40 characters"
#Using a dictionary to create a map for passing
results_dict = {
"year": "2018",
"pkg": "textwrap",
"word_list": ""
}
wrapper = textwrap.TextWrapper(width=40)
results_dict["word_list"] = wrapper.fill(text=text_string)
new_string = """This is a new string formatted in {year} with {pkg} resulting in \n{word_list}""".format(**results_dict)
#using the **results_dict as a map just to show another method for format
print(new_string)
In this case, fill just returns a wrapped version (string) of the given paragraph or sentence so we just need to pass that as normally.
Output of both:
This is a new string formatted in 2018 with textwrap resulting in
This is a long string that goes beyond
40 characters

How to place dots into the number with Python?

How can I automatically place dots by separating it with 3 digits in a group beginning from the right?
Example:
in: 1234; out 1.234
in: 12345678; out 12.345.678
You are looking for a thousands-separator. Format your number with the format() function to using commas as the thousands separator, then replace the commas with dots:
>>> format(1234, ',').replace(',', '.')
'1.234'
>>> format(12345678, ',').replace(',', '.')
'12.345.678'
Here the ',' format signals that the decimal number should be formatted with a thousands-separator (see the Format Specification Mini-language).
The same can be achieved in a wider string format with the str.format() method, where placeholders in the template are replaced with values:
>>> 'Some label for the value: {:,}'.format(1234).replace(',', '.')
'Some label for the value: 1,234'
but then you run the risk of accidentally replacing other full stops in the output string too!
Your other option would be to use the locale-dependent 'n' format, but that requires your machine to be configured for a locale that sets the right LC_NUMERIC options.
Here is a simple solution:
>>> a = 12345678
>>> "{:,}".format(a)
'12,345,678'
>>> "{:,}".format(a).replace(",", ".")
'12.345.678'
>>>
This uses the .format method of a string to add the comma separators and then the .replace method to change those commas to periods.

Categories

Resources