Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

Python: Str Position?

i am learning from python online course regarding open & read file. Stumble upon one of the code line

data = "{:^13} {:<11} {:<6} "

One of the response obtained as below. However, I am still not clear of the following

  1. In the response, it is mentioned which will come at position of 13 , 11 and 6

What does it mean by position? is it similar to index?

  1. what does the notation "^", "<" and {:} represent?

  2. why use eg {:^13} instead of str(data.format(rnd10000,9999)

unclear clarification

Thank you for the post!

data = "{:^13} {:<11} {:<6}
" this will be printed as string which will be formatted using the random number between 10000 9999 , which will come at position of 13 , 11 and 6

Happy learning!

Code as below

from random import randint as rnd

memReg = 'members.txt'
exReg = 'inactive.txt'
fee =('yes','no')

def genFiles(current,old):
    with open(current,'w+') as writefile: 
        writefile.write('Membership No  Date Joined  Active  
')
        data = "{:^13}  {:<11}  {:<6}
"

        for rowno in range(20):
            date = str(rnd(2015,2020))+ '-' + str(rnd(1,12))+'-'+str(rnd(1,25))
            writefile.write(data.format(rnd(10000,99999),date,fee[rnd(0,1)]))
question from:https://stackoverflow.com/questions/65557514/python-str-position

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lets try something a little more simple and take it apart step by step, to see why it's happening:

data = "{:^13} {:<11} {:<6}
"
print(data.format(1,2,3))
>>>      1       2           3     

>>>
  1. The notation ":^" center-aligns the value.

  2. The notation ":<" left-aligns the value.

Can we understand why the string looks like that now? Yes! Absolutely:

>>> "{:^13}".format(1)
'      1      '
>>> len('      1      ')
13

The first part of the formatted string is 13 characters long with whatever you pass into it - centered ({:^13}).

>>> "{:<11}".format(2)
'2          '
>>> len('2          ')
11
>>> "{:<6}".format(3)
'3     '
>>> len('3     ')
6

The 2nd part of the formatted string is 11 characters long and the 3rd part is 6 characters long because we prepend whitespaces (note that it does not have to be whitespaces! You can choose the character that will be used for padding by writing it before the < sign like this: {:_<11} -> now we would prepend _) until we have 11 and 6 characters in the strings respectively.

We can confirm that that is what is happening by counting them together: 13 + 11 + 6 + 2 Whitespaces inbetween brackets + 1 New line = 33

>>> len(data.format(1,2,3))
33

Okay, so we fully understand why the string got formatted how it did, but now comes your question why use this way of formatting instead of using that way of formatting. Python does offer a ton of way to format data but when it comes to the string .format() method there is one article that I would recommend to everyone:

https://pyformat.info/

There you will find a lot of comparisons between old-style formatting methods and the .format() method. Not everything is possible with both and even aside from that, there are a lot of differences. I think you should be able to find all of the answers there as well.

Last but not least, @ShadowRanger already provided you the actual documentation with all nuances and details about the formatting "mini-language". While not as beginner friendly, it's a good habit to always read the documentation first when trying to understand how someones code is working.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...