-2

Hi there I've had a search output formats and formats had no luck. I couldn't find right documentation for it and I really want to learn how this code works if somebody could enlighten me please?

    print ("Survived: %i (%.1f%%)"%(len(survived), float(len(survived))/len(train)*100.0))
print ("Not Survived: %i (%.1f%%)"%(len(not_survived), float(len(not_survived))/len(train)*100.0))
print ("Total: %i"%len(train))

My questions is inside the code % symbols %i %.1f%% (I believe one decimal) I just really struggle understanding this code how it works (%%%) wise. if somebody could break down for me.

Output is:

Survived: 342 (38.4%)
Not Survived: 549 (61.6%)
Total: 891

Thank you.

Sorunlu
  • 13
  • 5
  • 1
    `%i` is an integer. `%.1f` is a float with 1 decimal place. `%%` is a percent sign. https://docs.python.org/3.4/library/string.html#format-specification-mini-language – 001 Oct 29 '20 at 17:18
  • 1
    What is %% for in Python? [duplicate]: https://stackoverflow.com/questions/25901852/what-is-for-in-python – Bruck1701 Oct 29 '20 at 17:18
  • 1
    Google "python string percent" – Alex Hall Oct 29 '20 at 17:18
  • Thank you for your fast reply John, I've had a look on internet I couldn't find doc. for it. is this belongs to python 2.7? – Sorunlu Oct 29 '20 at 17:18

1 Answers1

1

Python supports different ways of formatting strings. Unfortunately, they are not all in the same place in the documentation. So, I guess it makes sense to put them all in one SO answer :)

What you have in the question is printf-style formatting using the modulo (%) operator. For the specification of that see printf-style String Formatting.

Example:

x = 9
print('value of x is %d' % x)

For formatting using the format function, see Format String Syntax.

Example:

x = 9
print('value of x is {x}'.format(x=x))

The same syntax is used as basis for f-strings. See PEP-0498.

Example:

x = 9
print(f'value of x is {x}')

There are also template strings, see Template strings specification. Example:

x = 9
print(string.Template('value of x is $x').substitute(x=x))
zvone
  • 18,045
  • 3
  • 49
  • 77