在打印时如何用零填充一个数字?

huangapple go评论75阅读模式
英文:

How to pad a number with zeros when printing?

问题

你可以使用字符串的格式化方法来实现数字或字符串的零填充,以使其具有固定的宽度。

对于你的例子,如果你有数字12,想要将其变为000012,你可以使用以下代码:

number = 12
width = 6
padded_number = str(number).zfill(width)
print(padded_number)

这里,str(number)将数字转换为字符串,然后使用.zfill(width)方法在字符串的左侧填充零,使其总宽度为width。最后,使用print语句打印结果。

希望这可以帮助到你!

英文:

How can I print a number or make a string with zero padding to make it fixed width?

For instance, if I have the number 12 and I want to make it 000012.

答案1

得分: 319

fmt包可以为您完成这个任务:

fmt.Printf("|%06d|%6d|\n", 12, 345)

输出结果:

|000012|   345|

请注意%06d中的0,它将使宽度为6,并用零填充。第二个将用空格填充。

在这里尝试一下:http://play.golang.org/p/cinDspMccp

英文:

The fmt package can do this for you:

fmt.Printf("|%06d|%6d|\n", 12, 345)

Output:

|000012|   345|

Notice the 0 in %06d, that will make it a width of 6 and pad it with zeros. The second one will pad with spaces.

Try it for yourself here: http://play.golang.org/p/cinDspMccp

答案2

得分: 128

使用 fmt 包 中的 Printf 函数,设置 width6,填充字符为 0

import "fmt"
fmt.Printf("%06d", 12) // 输出到标准输出 '000012'

通过在格式说明符('verb')之前直接添加一个整数来设置 width

fmt.Printf("%d", 12)   // 使用默认的 width,输出 '12'
fmt.Printf("%6d", 12)  // 使用 width 为 6,并在左侧填充空格,输出 '    12'

Golang(以及大多数其他语言)只支持空格和 0 作为 填充字符

fmt.Printf("%6d", 12)   // 默认填充字符为空格,输出 '    12'
fmt.Printf("%06d", 12)  // 改为使用 0 进行填充,输出 '000012'

可以通过在格式说明符之前添加减号 - 来实现 右对齐

fmt.Printf("%-6d", 12)   // 右对齐填充,输出 '12    '

请注意,对于 浮点数,width 包括整个格式字符串:

fmt.Printf("%06.1f", 12.0) // 输出 '0012.0'(width 为 6,精度为 1 位小数)

还可以通过使用 * 而不是数字,并将 width 作为 int 参数传递来动态设置 width:

myWidth := 6
fmt.Printf("%0*d", myWidth, 12) // 如前所述,输出 '000012'

这在某些情况下非常有用,例如,如果要打印的最大值只在运行时已知(在下面的示例中称为 maxVal):

myWidth := 1 + int(math.Log10(float64(maxVal)))
fmt.Printf("%*d", myWidth, nextVal)

最后,如果不想输出到标准输出而是返回一个字符串,请使用同样参数的 fmt 包 中的 Sprintf 函数:

s := fmt.Sprintf("%06d", 12) // 返回字符串 '000012'
英文:

Use the Printf function from the fmt package with a width of 6 and the padding character 0:

import "fmt"
fmt.Printf("%06d", 12) // Prints to stdout '000012'

Setting the width works by putting an integer directly preceding the format specifier ('verb'):

fmt.Printf("%d", 12)   // Uses default width,                          prints '12'
fmt.Printf("%6d", 12)  // Uses a width of 6 and left pads with spaces, prints '    12'

The only padding characters supported by Golang (and most other languages) are spaces and 0:

fmt.Printf("%6d", 12)   // Default padding is spaces, prints '    12'
fmt.Printf("%06d", 12)  // Change to 0 padding,       prints '000012'

It is possible to right-justify the printing by prepending a minus -:

fmt.Printf("%-6d", 12)   // Padding right-justified, prints '12    '

Beware that for floating point numbers the width includes the whole format string:

fmt.Printf("%06.1f", 12.0) // Prints '0012.0' (width is 6, precision is 1 digit)

It is useful to note that the width can also be set programmatically by using * instead of a number and passing the width as an int parameter:

myWidth := 6
fmt.Printf("%0*d", myWidth, 12) // Prints '000012' as before

This might be useful for instance if the largest value you want to print is only known at runtime (called maxVal in the following example):

myWidth := 1 + int(math.Log10(float64(maxVal)))
fmt.Printf("%*d", myWidth, nextVal)

Last, if you don't want to print to stdout but return a String, use Sprintf also from fmt package with the same parameters:

s := fmt.Sprintf("%06d", 12) // returns '000012' as a String

答案3

得分: 39

有一种最简单的方法可以实现这个。使用以下代码:

func padNumberWithZero(value uint32) string {
    return fmt.Sprintf("%02d", value)
}

fmt.Sprintf 格式化并返回一个字符串,而不会在任何地方打印它。这里的 %02d 表示在值的左边填充零,如果给定的值的位数小于 2。如果给定的值有 2 个或更多位数,它将不会填充零。例如:

  • 如果输入是 1,输出将是 01。
  • 如果输入是 12,输出将是 12。
  • 如果输入是 1992,输出将是 1992。

你可以使用 %03d 或更多的数字来进行更多的零填充。

英文:

There is one simplest way to achieve this. Use

func padNumberWithZero(value uint32) string {
    return fmt.Sprintf("%02d", value)
}

fmt.Sprintf formats and returns a string without printing it anywhere.
Here %02d says pad zero on left for value who has < 2 number of digits. If given value has 2 or more digits it will not pad. For example:

  • If input is 1, output will be 01.
  • If input is 12, output will be 12.
  • If input is 1992, output will be 1992.

You can use %03d or more for more zeros padding.

答案4

得分: 13

只是以防万一,如果你想通过连接前缀或后缀来形成另一个单词,你可以使用下面的代码。

package main

import "fmt"

func main() {
    concatenatedWord := "COUNTER_" + fmt.Sprintf("%02d", 1)
    // 使用 concatenatedWord
    fmt.Println("ConcatenatedWordword is", concatenatedWord)
}

输出:ConcatenatedWordword is COUNTER_01

链接:https://play.golang.org/p/25g3L8TXiPP

英文:

Just in case if you want to prefix or suffix to form another word by concatenating you can use below code.

package main

import &quot;fmt&quot;

func main() {
	concatenatedWord:= &quot;COUNTER_&quot;+fmt.Sprintf(&quot;%02d&quot;, 1)
	// use concatenatedWord 
        fmt.Println(&quot;ConcatenatedWordword is&quot;, concatenatedWord)
}

output : ConcatenatedWordword is COUNTER_01

link : https://play.golang.org/p/25g3L8TXiPP

答案5

得分: 12

Go语言中的打印格式列表”这个问题提醒我们还有一个标志:

> - 使用空格在右侧填充而不是左侧(左对齐字段)


如果你想使用其他字符串序列进行填充(比'0'或' '更复杂),你可以在DaddyOh/golang-samples/pad.go中找到更多的填充示例:

  • leftPad(s string, padStr string, pLen int)
  • rightPad(s string, padStr string, pLen int)
  • leftPad2Len(s string, padStr string, overallLen int)
  • rightPad2Len(s string, padStr string, overallLen int)

请参见<kbd>play.golang.org</kbd>

1234567890

leftPad(str, &quot;*&quot;, 3)  ***1234567890
leftPad2Len(str, &quot;*-&quot;, 13)  -*-1234567890
leftPad2Len(str, &quot;*-&quot;, 14)  *-*-1234567890
leftPad2Len(str, &quot;*&quot;, 14)  ****1234567890
leftPad2Len(str, &quot;*-x&quot;, 14)  x*-x1234567890
leftPad2Len(str, &quot;ABCDE&quot;, 14)  BCDE1234567890
leftPad2Len(str, &quot;ABCDE&quot;, 4)  7890
rightPad(str, &quot;*&quot;, 3)  1234567890***
rightPad(str, &quot;*!&quot;, 3)  1234567890*!*!*!
rightPad2Len(str, &quot;*-&quot;, 13)  1234567890*-*
rightPad2Len(str, &quot;*-&quot;, 14)  1234567890*-*-
rightPad2Len(str, &quot;*&quot;, 14)  1234567890****
rightPad2Len(str, &quot;*-x&quot;, 14)  1234567890*-x*
rightPad2Len(str, &quot;ABCDE&quot;, 14)  1234567890ABCD
rightPad2Len(str, &quot;ABCDE&quot;, 4)  1234
英文:

The question "List of printing format in Go lang" reminds us that there is also the flag:

> - pad with spaces on the right rather than the left (left-justify the field)


You can see more padding examples with DaddyOh/golang-samples/pad.go, if you want to pad with other string sequences (more complex than '0' or ' '):

  • leftPad(s string, padStr string, pLen int)
  • rightPad(s string, padStr string, pLen int)
  • leftPad2Len(s string, padStr string, overallLen int)
  • rightPad2Len(s string, padStr string, overallLen int)

See <kbd>play.golang.org</kbd>:

1234567890

leftPad(str, &quot;*&quot;, 3)  ***1234567890
leftPad2Len(str, &quot;*-&quot;, 13)  -*-1234567890
leftPad2Len(str, &quot;*-&quot;, 14)  *-*-1234567890
leftPad2Len(str, &quot;*&quot;, 14)  ****1234567890
leftPad2Len(str, &quot;*-x&quot;, 14)  x*-x1234567890
leftPad2Len(str, &quot;ABCDE&quot;, 14)  BCDE1234567890
leftPad2Len(str, &quot;ABCDE&quot;, 4)  7890
rightPad(str, &quot;*&quot;, 3)  1234567890***
rightPad(str, &quot;*!&quot;, 3)  1234567890*!*!*!
rightPad2Len(str, &quot;*-&quot;, 13)  1234567890*-*
rightPad2Len(str, &quot;*-&quot;, 14)  1234567890*-*-
rightPad2Len(str, &quot;*&quot;, 14)  1234567890****
rightPad2Len(str, &quot;*-x&quot;, 14)  1234567890*-x*
rightPad2Len(str, &quot;ABCDE&quot;, 14)  1234567890ABCD
rightPad2Len(str, &quot;ABCDE&quot;, 4)  1234

答案6

得分: 6

func lpad(s string, pad string, plength int) string {
    for i := len(s); i < plength; i++ {
        s = pad + s
    }
    return s
}

lpad("3", "0", 2)  结果: "03"

lpad("12", "0", 6)  结果: "000012"

以上是要翻译的内容。

英文:
func lpad(s string,pad string, plength int)string{
	for i:=len(s);i&lt;plength;i++{
		s=pad+s
	}
	return s
}

lpad("3","0",2) result: "03"

lpad("12","0",6) result: "000012"

答案7

得分: 2

这是我的解决方案:

func leftZeroPad(number, padWidth int64) string {
	return fmt.Sprintf(fmt.Sprintf("%%0%dd", padWidth), number)
}

示例用法:

fmt.Printf("%v", leftZeroPad(12, 10))

输出:

0000000012

这种方法的优点是,如果需要,你可以在运行时指定填充长度。

英文:

Here's my solution:

func leftZeroPad(number, padWidth int64) string {
	return fmt.Sprintf(fmt.Sprintf(&quot;%%0%dd&quot;, padWidth), number)
}

Example usage:

fmt.Printf(&quot;%v&quot;, leftZeroPad(12, 10))

prints:

0000000012

The advantage of this is that you can specify the pad length at run time if needed.

答案8

得分: 1

对于那些想要进行右侧填充的人,可以按照以下方式操作:

str2pad := "12"
padWith := "0"
amt2pad := 6

// 这将确保总共有6个字符,右侧填充
// 注意检查 strings.Repeat 是否返回负值
paddedStr := str2pad + strings.Repeat(padWith, amt2pad-len(str2pad))

// 输出 120000

以上代码将确保 paddedStr 总共有6个字符,并在右侧进行填充,输出结果为 120000

英文:

For those that want to right pad, you can do this:

str2pad := &quot;12&quot;
padWith := &quot;0&quot;
amt2pad := 6

//This will make sure there is always 6 characters total, padded on the right side
//Note to check if strings.Repeat returns a negative value
paddedStr := str2pad + strings.Repeat(padWith, amt2pad - len(str2pad))

//Outputs 120000

答案9

得分: 1

另一个选项是golang.org/x/text/number包:

package main

import (
   "golang.org/x/text/language"
   "golang.org/x/text/message"
   "golang.org/x/text/number"
)

var fmt = message.NewPrinter(language.English)

func main() {
   n := number.Decimal(
      12, number.Pad('0'), number.FormatWidth(6),
   )
   fmt.Println(n) // 000012
}

https://pkg.go.dev/golang.org/x/text/number

英文:

Another option is the golang.org/x/text/number package:

package main

import (
   &quot;golang.org/x/text/language&quot;
   &quot;golang.org/x/text/message&quot;
   &quot;golang.org/x/text/number&quot;
)

var fmt = message.NewPrinter(language.English)

func main() {
   n := number.Decimal(
      12, number.Pad(&#39;0&#39;), number.FormatWidth(6),
   )
   fmt.Println(n) // 000012
}

https://pkg.go.dev/golang.org/x/text/number

答案10

得分: 0

fmt.Printf("%012s", "345")

结果:000000000345

英文:
fmt.Printf(&quot;%012s&quot;, &quot;345&quot;)

Result: 000000000345

huangapple
  • 本文由 发表于 2014年9月3日 14:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/25637440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定