Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What are % and %s?
#1
I am just a beginner. I am slowly working my way through 'How to Automate the Boring Stuff' by Al Sweigart

In the code below, I can't see what the %s is, or %
The code works ok, to my amazement, I'd just like to know why in quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w') quizNum is %s from the loop in the text part, because it correctly creates capitalsquiz1.txt and so on. How does this work? Why write %s? What is %? I understand (quizNum + 1), because range begins at 0.
As far as I know, python has % as modulo like 22 % 8 = 6

# Generate 35 quiz files.

for quizNum in range(35):

# Create the quiz and answer key files.

    quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')       
    answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')
Reply
#2
for quiz_num in range(2):
    print("The old way,don't use it' <%s>" % quiz_num)

for quiz_num in range(2):
    print('A newer way format(),ten year old comes out with 2.6 <{}>'.format(quiz_num))

for quiz_num in range(2):
    print(f'The new way f-string 3.6 <{quiz_num}>')
Output:
The old way,don't use it' <0> The old way,don't use it' <1> A newer way format(),ten year old comes out with 2.6 <0> A newer way format(),ten year old comes out with 2.6 <1> The new way f-string 3.6 <0> The new way f-string 3.6 <1>
Reply
#3
No this is not modulo. This is "string formatting" and the best way to use variable contents in a string template.
Why write it like this? So you do not do the even older way (don't use it) of combining template and variables in a completely unreadable manner like many beginners first do (because they don't know this advanced string formatting)
world = 'Poland'
today = 'Tuesday, 23. August'
print('Hello ' + world + '! How are you ' + today + '?')
Reply
#4
(Aug-21-2017, 10:03 AM)Pedroski55 Wrote: I am just a beginner. I am slowly working my way through 'How to Automate the Boring Stuff' by Al Sweigart

In the code below, I can't see what the %s is, or %

Hey! I am just a beginner too, but i started out with going through this neat beginnersguide:
learnpythonthehardway.org/book/

This tutorial goes very nicely through things like this, and I went on to learn more python alot faster than I would have if I didn't start here :)

Good luck!

- andre
Reply
#5
Hi andre, welcome to Python!

If you like neat guides, check our recommendations of free Python ressources

The book you mentioned is a bit disputed, as it teaches some controversial habits while leaving out other important concepts alltogether.

Glad it helped you start though :)
Reply
#6
Hi Kebap

This is all new to me, thank you so much for the enlightenment! :)
Reply


Forum Jump:

User Panel Messages

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