• This repository has been archived on 01/Mar/2024
  • Stars
    star
    131
  • Rank 267,678 (Top 6 %)
  • Language
    Julia
  • License
    Other
  • Created over 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Deprecated. See README. (A Julia package to provide Python-like formatting support)

Formatting

This package offers Python-style general formatting and c-style numerical formatting (for speed).

PackageEvaluator Build Status

Getting Started

This package is pure Julia. Setting up this package is like setting up other Julia packages:

Pkg.add("Formatting")

To start using the package, you can simply write

using Formatting

This package depends on Julia of version 0.7 or above. It has no other dependencies. The package is MIT-licensed.

Python-style Types and Functions

Types to Represent Formats

This package has two types FormatSpec and FormatExpr to represent a format specification.

In particular, FormatSpec is used to capture the specification of a single entry. One can compile a format specification string into a FormatSpec instance as

fspec = FormatSpec("d")
fspec = FormatSpec("<8.4f")

Please refer to Python's format specification language for details.

FormatExpr captures a formatting expression that may involve multiple items. One can compile a formatting string into a FormatExpr instance as

fe = FormatExpr("{1} + {2}")
fe = FormatExpr("{1:d} + {2:08.4e} + {3|>abs2}")

Please refer to Python's format string syntax for details.

Note: If the same format is going to be applied for multiple times. It is more efficient to first compile it.

Formatted Printing

One can use printfmt and printfmtln for formatted printing:

  • printfmt(io, fe, args...)

  • printfmt(fe, args...)

    Print given arguments using given format fe. Here fe can be a formatting string, an instance of FormatSpec or FormatExpr.

    Examples

    printfmt("{1:>4s} + {2:.2f}", "abc", 12) # --> print(" abc + 12.00")
    printfmt("{} = {:#04x}", "abc", 12) # --> print("abc = 0x0c") 
    
    fs = FormatSpec("#04x")
    printfmt(fs, 12)   # --> print("0x0c")
    
    fe = FormatExpr("{} = {:#04x}")
    printfmt(fe, "abc", 12)   # --> print("abc = 0x0c")

    Notes

    If the first argument is a string, it will be first compiled into a FormatExpr, which implies that you can not use specification-only string in the first argument.

    printfmt("{1:d}", 10)   # OK, "{1:d}" can be compiled into a FormatExpr instance
    printfmt("d", 10)       # Error, "d" can not be compiled into a FormatExpr instance
                            # such a string to specify a format specification for single argument
    
    printfmt(FormatSpec("d"), 10)  # OK
    printfmt(FormatExpr("{1:d}", 10)) # OK
  • printfmtln(io, fe, args...)

  • printfmtln(fe, args...)

    Similar to printfmt except that this function print a newline at the end.

Formatted String

One can use fmt to format a single value into a string, or format to format one to multiple arguments into a string using an format expression.

  • fmt(fspec, a)

    Format a single value using a format specification given by fspec, where fspec can be either a string or an instance of FormatSpec.

  • format(fe, args...)

    Format arguments using a format expression given by fe, where fe can be either a string or an instance of FormatSpec.

Difference from Python's Format

At this point, this package implements a subset of Python's formatting language (with slight modification). Here is a summary of the differences:

  • g and G for floating point formatting have not been supported yet. Please use f, e, or E instead.

  • The package currently provides default alignment, left alignment < and right alignment >. Other form of alignment such as centered alignment ^ has not been supported yet.

  • In terms of argument specification, it supports natural ordering (e.g. {} + {}), explicit position (e.g. {1} + {2}). It hasn't supported named arguments or fields extraction yet. Note that mixing these two modes is not allowed (e.g. {1} + {}).

  • The package provides support for filtering (for explicitly positioned arguments), such as {1|>lowercase} by allowing one to embed the |> operator, which the Python counter part does not support.

C-style functions

The c-style part of this package aims to get around the limitation that @sprintf has to take a literal string argument. The core part is basically a c-style print formatter using the standard @sprintf macro. It also adds functionalities such as commas separator (thousands), parenthesis for negatives, stripping trailing zeros, and mixed fractions.

Usage and Implementation

The idea here is that the package compiles a function only once for each unique format string within the Formatting.* name space, so repeated use is faster. Unrelated parts of a session using the same format string would reuse the same function, avoiding redundant compilation. To avoid the proliferation of functions, we limit the usage to only 1 argument. Practical consideration would suggest that only dozens of functions would be created in a session, which seems manageable.

Usage

using Formatting

fmt = "%10.3f"
s = sprintf1( fmt, 3.14159 ) # usage 1. Quite performant. Easiest to switch to.

fmtrfunc = generate_formatter( fmt ) # usage 2. This bypass repeated lookup of cached function. Most performant.
s = fmtrfunc( 3.14159 )

s = format( 3.14159, precision=3 ) # usage 3. Most flexible, with some non-printf options. Least performant.

Speed

sprintf1: Speed penalty is about 20% for floating point and 30% for integers.

If the formatter is stored and used instead (see the example using generate_formatter above), the speed penalty reduces to 10% for floating point and 15% for integers.

Commas

This package also supplements the lack of thousand separator e.g. "%'d", "%'f", "%'s".

Note: "%'s" behavior is that for small enough floating point (but not too small), thousand separator would be used. If the number needs to be represented by "%e", no separator is used.

Flexible format function

This package contains a run-time number formatter format function, which goes beyond the standard sprintf functionality.

An example:

s = format( 1234, commas=true ) # 1,234
s = format( -1234, commas=true, parens=true ) # (1,234)

The keyword arguments are (Bold keywards are not printf standard)

  • width. Integer. Try to fit the output into this many characters. May not be successful. Sacrifice space first, then commas.
  • precision. Integer. How many decimal places.
  • leftjustified. Boolean
  • zeropadding. Boolean
  • commas. Boolean. Thousands-group separator.
  • signed. Boolean. Always show +/- sign?
  • positivespace. Boolean. Prepend an extra space for positive numbers? (so they align nicely with negative numbers)
  • parens. Boolean. Use parenthesis instead of "-". e.g. (1.01) instead of -1.01. Useful in finance. Note that you cannot use signed and parens option at the same time.
  • stripzeros. Boolean. Strip trailing '0' to the right of the decimal (and to the left of 'e', if any ).
    • It may strip the decimal point itself if all trailing places are zeros.
    • This is true by default if precision is not given, and vice versa.
  • alternative. Boolean. See # alternative form explanation in standard printf documentation
  • conversion. length=1 string. Default is type dependent. It can be one of aAeEfFoxX. See standard printf documentation.
  • mixedfraction. Boolean. If the number is rational, format it in mixed fraction e.g. 1_1/2 instead of 3/2
  • mixedfractionsep. Default _
  • fractionsep. Default /
  • fractionwidth. Integer. Try to pad zeros to the numerator until the fractional part has this width
  • tryden. Integer. Try to use this denominator instead of a smaller one. No-op if it'd lose precision.
  • suffix. String. This strings will be appended to the output. Useful for units/%
  • autoscale. Symbol, default :none. It could be :metric, :binary, or :finance.
    • :metric implements common SI symbols for large and small numbers e.g. M, k, ΞΌ, n
    • :binary implements common ISQ symbols for large numbers e.g. Ti, Gi, Mi, Ki
    • :finance implements common finance/news symbols for large numbers e.g. b (billion), m (millions)

See the test script for more examples.

More Repositories

1

JLD2.jl

HDF5-compatible file format in pure Julia
Julia
531
star
2

HDF5.jl

Save and load data in the HDF5 file format from Julia
Julia
377
star
3

JSON.jl

JSON parsing and printing
Julia
305
star
4

MAT.jl

Julia module for reading MATLAB files
Julia
275
star
5

JLD.jl

Saving and loading julia variables while preserving native types
Julia
273
star
6

FileIO.jl

Main Package for IO, loading all different kind of files
Julia
205
star
7

ProtoBuf.jl

Julia protobuf implementation
Julia
200
star
8

BSON.jl

Julia
157
star
9

VideoIO.jl

Reading and writing of video files in Julia via ffmpeg
Julia
123
star
10

EzXML.jl

XML/HTML handling tools for primates
Julia
117
star
11

Suppressor.jl

Julia macros for suppressing and/or capturing output (STDOUT), warnings (STDERR) or both streams at the same time.
Julia
117
star
12

Zarr.jl

Julia
108
star
13

Parquet.jl

Julia implementation of Parquet columnar file format reader
Julia
108
star
14

LightXML.jl

A light-weight Julia package for XML based on libxml2.
Julia
88
star
15

TranscodingStreams.jl

Simple, consistent interfaces for any codec.
Julia
82
star
16

MeshIO.jl

IO for Meshes
Roff
78
star
17

Tar.jl

TAR files: create, list, extract them in pure Julia
Julia
78
star
18

LibSerialPort.jl

Julia wrapper for the libserialport c library
Julia
62
star
19

MsgPack.jl

Julia MsgPack implementation with type-driven, overloadable packing/unpacking functionality
Julia
59
star
20

ImageMagick.jl

Thin Wrapper for the library ImageMagick
Julia
51
star
21

CodecZlib.jl

zlib codecs for TranscodingStreams.jl.
Julia
50
star
22

ConfParser.jl

Julia package for parsing configuration files
Julia
41
star
23

BufferedStreams.jl

Fast composable IO streams
Julia
41
star
24

Sixel.jl

The Julia wrapper of libsixel
Julia
40
star
25

GZip.jl

A Julia interface for gzip functions in zlib
Julia
38
star
26

FFMPEG.jl

Julia Package for the FFMPEG builder binaries
Julia
34
star
27

SerialPorts.jl

SerialPort IO streams in Julia backed by pySerial.
Julia
31
star
28

Blosc.jl

Blosc compression for the Julia language
Julia
28
star
29

ImageIO.jl

Load images in Julia. Designed for FileIO interaction. Supports PNG and Portable Bitmap formats
Julia
27
star
30

MultifileArrays.jl

Create a higher-dimensional array from lazily-loaded slices in separate files
Julia
23
star
31

CodecZstd.jl

A zstd codec for TranscodingStreams.jl.
Julia
22
star
32

StructIO.jl

Experimental new implementation of StrPack.jl-like functionality
Julia
22
star
33

GoogleDrive.jl

Automate Google-Drive download in Julia
Julia
22
star
34

Pcap.jl

libpcap implementation for Julia language
Julia
20
star
35

FileTypes.jl

Small and dependency-free Julia package to infer file and MIME type checking the magic numbers signature.
Julia
18
star
36

PNGFiles.jl

FileIO.jl integration for PNG files
Julia
18
star
37

CBOR.jl

A Concise Binary Object Representation (RFC 7049) serialization library in Julia
Julia
18
star
38

Snappy.jl

A fast compressor/decompressor
Julia
15
star
39

IniFile.jl

Reading and writing Windows-style INI files (writing not yet implemented).
Julia
14
star
40

JpegTurbo.jl

Julia interface to libjpeg-turbo
Julia
14
star
41

HexEdit.jl

Julia package for editing and displaying binary file data in hexadecimal format
Julia
13
star
42

ArgTools.jl

Tools for writing functions that handle many kinds of IO arguments
Julia
13
star
43

WidthLimitedIO.jl

A Julia IO type that facilitates width-limited printing
Julia
12
star
44

QuartzImageIO.jl

Exposes macOS's native image IO functionality to Julia
Julia
12
star
45

GIFImages.jl

Provides Gif support in Julia using LibGif
Julia
12
star
46

NRRD.jl

Julia support for the Nearly Raw Raster Data (NRRD) image file format
Julia
10
star
47

ZeissMicroscopyFormat.jl

Importing the Zeiss CZI file format for microscopy
Julia
9
star
48

CodecLz4.jl

Transcoding codecs for compression and decompression with LZ4
Julia
9
star
49

ZipArchives.jl

Read and write Zip archive files in Julia.
Julia
9
star
50

FLAC.jl

Julia bindings for libFLAC
Julia
9
star
51

LibExpat.jl

Julia interface to the Expat XML parser library
Julia
8
star
52

CodecBzip2.jl

A bzip2 codec for TranscodingStreams.jl.
Julia
8
star
53

ImgHdr.jl

Library to Check Type of Image
Julia
7
star
54

CodecXz.jl

An xz codec for TranscodingStreams.jl.
Julia
7
star
55

CodecBase.jl

Base 16/32/64 codecs for TranscodingStreams.jl
Julia
7
star
56

CRC32.jl

CRC32 package for Julia
Julia
6
star
57

Telegram.jl

wrapper for the Telegram API in Julia (https://github.com/vysheng/tgl)
Julia
6
star
58

Toxcore.jl

Toxcore wrapper
Julia
6
star
59

VideoPlayer.jl

Video player for Julia
Julia
6
star
60

BSDiff.jl

Pure Julia port of bsdiff
Julia
5
star
61

HDF5Plugins.jl

Compression plugins for HDF5.jl implemented in Julia
Julia
5
star
62

libserialport

A mirror of libserialport for the provision of Windows binaries through CI
C
5
star
63

MetaImageFormat.jl

Support for reading MetaImage files in Julia
Julia
4
star
64

AndorSIF.jl

Read Andor SIF file in Julia
Julia
4
star
65

Netpbm.jl

Load and save Netpbm images in Julia
Julia
4
star
66

ImageMagickBuilder

binary deps for ImageMagick
Julia
3
star
67

Blosc2.jl

blosc2 wrapper for Julia lang
Julia
3
star
68

AdjustCRC.jl

adjust the CRC32/32c checksum of data to any desired value
Julia
3
star
69

AVSfldIO.jl

File IO for AVS .fld format data files
Julia
2
star
70

BSDiffTestData

Data for testing https://github.com/JuliaIO/BSDiff.jl
2
star
71

FFMPEGBuilder

BinaryBuilder repo for FFMPEG
Julia
2
star
72

LibpngBuilder

Julia
2
star
73

LibVPXBuilder

BinaryBuilder repo for LibVPX
Julia
2
star
74

x264Builder

BinaryBuilder repo for x264
Julia
2
star
75

YasmBuilder

BinaryBuilder repo for Yasm
Julia
2
star
76

LibJPEGBuilder

Julia
2
star
77

Roadmap

Roadmap for the JuliaIO Organization
2
star
78

SigMF.jl

The Signal Metadata Format
Julia
2
star
79

LibTIFFBuilder

Julia
2
star
80

LAMEBuilder

Julia
2
star
81

WavefrontObj.jl

Julia
2
star
82

nasmBuilder

Julia
2
star
83

LibVorbisBuilder

builder for libvorbis
Julia
2
star
84

JLDArchives.jl

A repository of Julia *.jld files for testing backwards compatibility
Julia
2
star
85

OggBuilder

BinaryBuilder repo for libogg
Julia
2
star
86

x265Builder

BinaryBuilder repo for x265
Julia
2
star
87

LibassBuilder

Julia
2
star
88

LibALSABuilder

BinaryBuilder repo for alsa-lib
Julia
2
star