Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of filling zeros in Python numbers / strings

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "Python digital / string zero filling method". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Sometimes when using Python, you want to zero a number or string, that is, to change "1" into an eight-digit "00000001". You can use the following method to fill zeros.

String zero padding:

You can use the zfill () function to add zeros to a string:

> str = "123" > print (str.zfill (8)) 00000123

You can also convert integers to characters to use zfill () to fill zeros:

> num = 123 > print (str (num) .zfill (8)) 00000123 numeric zero padding:

Zeros can be filled in a formatted way for numbers:

> number = 123 > zfnumber = "d"% number > print (zfnumber) 00000123 > type (zfnumber)

You can see that the formatted number type becomes a character type.

Python adds zeros to the output integer

There are some different digits of numbers, such as 1,22,333, 4444, which may be different as normal output as a number or a transferred string, and sometimes the output to text will cause trouble in subsequent processing. If you want to keep the number of digits the same, add 0 in front of it.

The operation is very simple, just convert it to a string with s = "d"% n.

Take a chestnut.

For n in range (1000): s = "d"% n print (s)

One small problem is that if the zero in d is missing, there will be a problem if it is written as% 4d.

This is the end of the introduction of "the method of filling zeros in Python numbers / strings". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report