Python Forum
Definition of .format? (Newbie question)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Definition of .format? (Newbie question)
#1
I'm completly new to python and I've only been learning it for about a week. I have over the last couple of days spent many hours watching tutorials and creating my own codes but there's this one thing I'm a little stuck upon. I will explain when we get there.


I'm having problems understanding how the .format works and what its uses are.

by definition I found this explanation.

Syntax : { } .format(value)

Parameters :
(value) : Can be an integer, floating point numeric constant, string, characters or even variables.

Returntype : Returns a formatted string with the value passed as parameter in the placeholder position.

This all seems well and good. However, in my partially self coded class example I can't figure out what the .format is used for.

Here is my code.
class meaning:
    def __init__(self,name,lastname,nickname):
     self.name = name
     self.lastname = lastname
     self.nickname = nickname
    def myfunc(self):
        return "{} {} {}".format(self.name, self.lastname,self.nickname)

dude1 = meaning ("John", "Cena" ,"The hulk")
dude2 = meaning ("Gordon", "Freeman", "MRMIME")

print (dude1.myfunc())
print (dude2.myfunc())
My question here is.

Why is .format necessary here? I found a tutorial suggesting I need to have it included and that I can't just use str instead. However, there are no digits in this function. Why do I need .format if it's just text?

Maybe I'm just very stupid, but I can't make sense of my own stuff. I just know I had to include it....

In this class however, I don't have .format included and it runs almost just the same.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def myfunc(self):
      print ("Hello, my name is " + self.name)

p1 = Person ("Pyke", 36)
p1.myfunc()

print(p1.name)
print(p1.age)
What have I missed?
Reply
#2
Because this
Quote:
      print ("Hello, my name is " + self.name)
is not pythonic. Not to mention messy. Especially if you have more than one you are "formatting" into the final string and at different indices. No one in python does it like this (at least not to format it).

This is much easier to read
"{} {} {}".format(self.name, self.lastname,self.nickname)
You can tell there are 3 inserts separated with a single space character. Its simple and easy to understand the string structure.

format also has a built-in mini language to allow extra things you can do to the final format without changing the variable itself
>>> num = 3.141592653589793
>>> '{:.2f}'.format(num)
'3.14'
>>> '{:.3f}'.format(num)
'3.142'
>>> '{:010.3f}'.format(num)
'000003.142'
>>> '{:10.2f}'.format(num)
'      3.14'
>>> '{:30}'.format(num)
'             3.141592653589793'
>>> '{:<30}'.format(num)
'3.141592653589793             '
>>> '{:,}'.format(123456789)
'123,456,789'
>>> '{0:b}'.format(255)
'11111111'
>>> num
3.141592653589793
more here
https://docs.python.org/3/library/string...i-language
Recommended Tutorials:
Reply
#3
Also as new user you should use f-string,it's the future.
f-string are far more readable and concise,less prone to error than other ways of formatting.
Not that new,2.5-year ago in Python 3.6 f-string was new.
num = 3.141592653589793
>>> print(f'Area of a circle is equal to {num:.2f} times the radius squared,eg circle radius 5 has area: {5**2 * num:.1f}')
Area of a circle is equal to 3.14 times the radius squared,eg circle radius 5 has area: 78.5

>>> name = 'f-string'
>>> print(f"String formatting is called {name.upper():*^20}")
String formatting is called ******F-STRING******

# f-strings can take any Python expressions inside the curly braces.
>>> cost = 99.75999
>>> finance = 50000
>>> print(f'Toltal cost {cost + finance:.2f}')
Toltal cost 50099.76
  
>>> for word in 'f-strings are cool'.split():
...     print(f'{word.upper():~^20}')
...
~~~~~F-STRINGS~~~~~~
~~~~~~~~ARE~~~~~~~~~
~~~~~~~~COOL~~~~~~~~
Reply
#4
Python is a very flexible language system. a great many things you might need to do have more than one way to do it. but, a particular way is often considered to be the best way to do each thing. this is referred to as "pythonic". usually, it is the way that best takes advantage of Python's great power. the community will often point you in that direction.

if you are new to programming and Python is your first programming language, it will be easy. if, like me, you programmed in other languages before (Python is probably my 20th language), then it can be harder since you will need to unlearn many of the things learned with other languages. try, as much as you can, to learn and follow the methods of pythonic programming. do not fear if it looks unfamiliar; just ask for any help you need. and welcome to the community. your new and great journey begins today.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
Thanks for all the replies! I will take all of your tips in consideration!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  mutable argument in function definition akbarza 1 423 Dec-15-2023, 02:00 PM
Last Post: deanhystad
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 652 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  error occuring in definition a class akbarza 3 636 Nov-26-2023, 09:28 AM
Last Post: Yoriz
  newbie question - can't make code work tronic72 2 626 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Newbie question about switching between files - Python/Pycharm Busby222 3 543 Oct-15-2023, 03:16 PM
Last Post: deanhystad
  determine parameter type in definition function akbarza 1 550 Aug-24-2023, 01:46 PM
Last Post: deanhystad
  Newbie.... run for cover. OpenCV question Stevolution2023 2 921 Apr-12-2023, 12:57 PM
Last Post: Stevolution2023
  numpy newbie question bcwilly_ca 4 1,127 Feb-10-2023, 05:55 PM
Last Post: jefsummers
  [split] Explain the python code in this definition Led_Zeppelin 1 711 Jan-13-2023, 10:20 PM
Last Post: deanhystad
  Explain the python code in this definition Led_Zeppelin 1 1,059 Oct-27-2022, 04:04 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020