string-formatting,d , Formatting a string in D

Formatting a string in D


Tag: string-formatting,d

I read on D's documentation that it's possible to format strings with arguments as print statements, such as the following:

float x = 100 / 3.0;
writefln("Number: %.*g", 2, x);

Number: 33.33

However, I'm wondering how I would do this if I just wanted the string equivalent, without printing it. I've looked at the std.format library but that seems way to messy for something I only need to use once. Is there anything a little bit more clear available?


Import std.string or std.format and use the format function.

import std.string;

void main()
    float x = 100 / 3.0;
    auto s = format("Number: %.*g", 4, x);
    assert(s == "Number: 33.33");


How to reference the empty string key in the Format String Syntax?

The empty string ('') is a pertectly valid key for a dictionary, but I can not reference it using the Format String Syntax data = { 'a' : 'hello' , '' : 'bye' } print '{a:<14s}'.format(**data) print '{:<14s}'.format(**data) Which outputs: hello Traceback (most recent call last): File "", line 3,...

Python format strings: 'Truncated incorrect DOUBLE value'

I format a string sql with sid (NOTE: the type of sid is str) sid = "34" #type(sid) is string, like 34, 34s sql = '''SELECT * FROM table_name WHERE sid={sid}'''.format(sid=sid) The result of print sql is: SELECT * FROM table_name WHERE sid=34 which is out of my expection (34...

How to pass tuple1 if … else tuple2 to str.format?

Put simply, why do I get the following error? >>> yes = True >>> 'no [{0}] yes [{1}]'.format((" ", "x") if yes else ("x", " ")) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of range I use python 2.6....

Parse an f-style interpolated string to recover arguments

What's the best way to create the complement for an f-style string interpolation, i.e. a way to parse the arguments/numbers in a formatted string? E.g. val format = "frame%04d.png" val i = 123 val out = f"frame$i%04d.png" assert(out == "frame0123.png") def parse(s: String, pat: String): Int = ??? val j...

Formatting a time value

In the following program I am returning a boolean value and a value representing the execution time in a tuple: import time # O(n) time def isAnagram1(s1, s2): start = time.time() letterlist1 = [0] * 26 letterlist2 = [0] * 26 for i in xrange(0, len(s1)): pos = ord(s1[i]) -...

When trying to include “ in a String, using \” works but the \ is included too

I'm trying to send a string to an Http request using the following code var outStr = "{product_code: \"660825\", quantity: \(qty)}" As I've included the \ character it compiles ok but when I run it the value for outStr is {product_code: \"660825\", quantity: 2} What am I doing wrong and...

Number formatting using php

I am using php. I want to display a number in a '$XX.XXX.XX' format. I tried the following code, but its not giving full output. <?php echo "$".number_format(round($customer['hourly_payment']),2); ?> Output $17,317.00 Please suggest a solution!...

Format operator removes line breaks

I have a text file like this: File: sample1.txt foo: {0} bar: {1} Hello {2} I run the following commands: $txt = gc Sample1.txt $txt -f "bar","foo","world" I got the output: foo: bar bar: foo Hello world Where did all the line breaks go?...

Log4j Implicit String Formatting

I am using log4j v1.2.14 for logging in my project and I am also using Java 7 String.format() to put variables in my output. Currently I am writing"Your var is [%s] and you are [%s]", myVar, myVar1)); Is this really the best way to output strings? I feel that...

What does %[^<] (and friends) mean in the formatted string family?

A comment (which should probably be submitted as an answer) has the code sscanf(string, "<title>%[^<]</title>", extracted_string); Running the code seems to copy the text between the <title> tags to extracted_string, but I cannot find any references to a caret in the printf family, either in the man pages or elsewhere...

Parsing into a string from type DateTime

I am trying to convert a DateTime and an int property into a string in a foreach loop. I need to put the information that is stored in the objects properties into the variables and then use that info to write to a text file using StreamWriter. I'm not quite...

Byte InputRange from file

How to construct easily a raw byte-by-byte InputRange/ForwardRange/RandomAccessRange from a file?

fprinf_s converts double to 0.0000

Lets keep it short. I've got the following snippet of code: double score = 9.987654 fopen_s(&output, "9.output.txt", "w"); fprintf_s(output, "%.4f", &score); fclose(output); It writes 0.0000 in 9.output.txt, where it should be printing 9.9876. Any idea of where is the problem?...

Can I operate on formatted strings?

A snippet of Python code: def someMethod(): return"%B" + " " + "%d".lstrip('0') + ", " + "%Y") How come this returns: June 03, 2015 And not what I expected, which was: June 3, 2015 Thanks for your help....

Including Parenthisis inside a VBA db.Execute String

How do I format this line of code correctly to allow me to have the parenthesis inside the statement string? db.Execute("SQL DB", "INSERT INTO ABPCahirMIS.dbo.TESTDB (TEST) VALUES(1) ") ...

Why is sscanf not reading the first argument in the format string?

In the following program, everything but the first value (the month) in the format string is being read into the SYSTEMTIME structure. Can anyone help me figure this one out? #include <Windows.h> #include <stdio.h> int main() { SYSTEMTIME st; char buf[50]; strcpy(buf, "6/23/2015 12:00:00"); sscanf(buf, "%d/%d/%d %d:%d:%d", &st.wMonth, &st.wDay, &st.wYear,...

show string in a desire format

I want to show my string in a special format. For example I have a string like this s = "00012345"; and want to show it in this format 000(123-45) I use this code for it: label1.text = string.format("{0,###(###-##)}",s); But just see this for result: 00012345. What string formatting should...

How do I, or can I use a static resource for the StringFormat on a TextBlock?

I have a text block that is displaying the date/time. The look of the clock may be different on some controls in the application, as far as color and maybe font, but I want the date and time to have the same format. I know I can set the StringFormat...

How to use libgit's git_repository_open in d

I am trying to use the libgit2 library in d. I always get a segmentation fault upon the the program's exit. The error does not happen before the exit, when I open and close the repository. It would seem that this is an issue with the garbage collector, but manually...

What does it mean that the D garbage collector is “not guaranteed to run the destructor for all unreferenced objects”?

The D documentation at states that "The garbage collector is not guaranteed to run the destructor for all unreferenced objects." However I am a little contused as to what this actually means. Is this saying that a GC implementation can choose to not call destructors when it collects the...

ZipArchive with embedded ZIP concated to EXE

In my gaming project, I implemented embedded ZIP resource file with the method described here in the second answer (using blob.S to embed & mark the ZIP): Is there any standard way of embedding resources into Linux executable image? In long run, I would like to simplify build process and...

How to format a floating number to fixed width with forced sign in Python

I'm trying to format a number to fixed width with a sign in Python - I can do one or the other but not both:'{:>5+.0f}'.format(43.5) doesn't work (ValueError: Invalid conversion specification) My current workaround is to do: '{:>5}'.format('{:+.0f}'.format(43.5)) But it doesn't seem very pretty - is there a way to...

Split a DNA sequence into a list of codons with D

DNA strings consist of an alphabet of four characters, A,C,G, and T Given a string, ATGTTTAAA I would like to split it in to its constituent codons ATG TTT AAA codons = ["ATG","TTT","AAA"] codons encode proteins and they are redundant ( I have a DNA string in D and would...

Intercompatibility between std.stdio.File and*

Is there any good way to turn a std.stdio.File into something that is an instance of a stream from Reason: I find myself wanting a generic logging utility working on streams, and I want to pass it std.stdio.stderr which is a std.stdio.File....

D Language Static Class Function Undefined Identifier

I started learning the D programming language(it's pretty awesome), and ran into a slight problem when I started to explore functions. The setup is pretty basic; it's just a way to figure out the similarities of the language to others that I have used. Here is my class declaration: module...

Extract substrings in python

I want to parse a string to extract all the substrings in curly braces: 'The value of x is {x}, and the list is {y} of len {}' should produce: (x, y) Then I want to format the string to print the initial string with the values: str.format('The value of...

How to fix D “memory leaks”

So I've been searching for a solution to this problem for some time. I've written a program to take data from two separate text files, parse it, and output to another text file and an ARFF file for analysis by Weka. The problem I'm running into is that the function...

Python str.format() — passing in list, outputting list

I haven't used str.format() much before and am wondering how to pass in list values and retrieve a list output with these values passed in. i.e. listex = range(0, 101, 25) baseurl = "https://thisisan{0}".format(*listex) I'd like a list output like ["", "", "", etc etc] but with my current code...

Pure constructors in class templates

I have some code that works, and I'm not sure why. I'm instantiating a class as an immutable variable. There are no immutable constructors in the class and none are labeled as pure, but it just works anyway. I also read that pure constructors can be used across the board...

Can this be done with formatting strings alone?

I think I've found something that can't be done with formatting strings alone: I'm needing a string that would allow me to format a double to show no decimals and so that: Numbers are thousand separated 0 shows a dash Negative numbers are shown between parentheses 0.5 is rounded to...

Delphi 7: Formatting changes after using delete procedure

I was working on my text editor, which I have completed, but I still have this one problem I'm trying to solve. My problem is, that I want to delete specific symbols on the end of lines, which were created by pressing the speedbutton (button is down). So when I...

Algorithm output to length starts new line

I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");,...

python dict in formated string [duplicate]

This question already has an answer here: How can I print a literal “{}” characters in python string and also use .format on it? 4 answers I want to write a python dictionary in a string. The values of the items should be give by the formated string. I...

D lang appending to multidimensional dynamic array

I want to append a 2D array to my 3D array. I expect it should be same as int[] arr; arr ~= 3; void readInput() { char[][][] candidate; char[] buff; size_t counter = 0; while ( stdin.readln(buff) ) { char[][] line = buff.chomp().split(); writeln(line); candidate ~= line; writeln(candidate); if (++counter...

Formatting a string in D

I read on D's documentation that it's possible to format strings with arguments as print statements, such as the following: float x = 100 / 3.0; writefln("Number: %.*g", 2, x); Number: 33.33 However, I'm wondering how I would do this if I just wanted the string equivalent, without printing it....

Can't connect to MySQL/MariaDB database from vibed app

All work fine if I use custom main ( void main() instead of shared static this() ). With default main I am getting "Access Violation" error. It's look like MySQL not allow connecting to it from localhost, but in my.ini I added string: bind-address = code, if it's help:...

How to format numeric string?

My text with not format is: 100000.00 I format it to: ("0:0,0 POINT") and I want it to: 100,000 POINT But I have no luck. So, how can it format it to 100,000 POINT? txtpoint.Text = string.Format("{0:0,0} POINT",(table_ca.Compute("SUM(POINT)", "")).ToString()); ...

JavaScript change format of a string, moving negative sign from the end to the front

I'm trying to format an output string from SAP, where they have negative sign placed at the end of the string. e.g 999.99- How can I use JavaScript or Groovy to adjusted this so that the negative numbers are formatted correctly? They should be -999.99 not 999.99-...

IOS: Get current date/time with specific (non-localized) format

I want to get the current date/time in a very specific format like this: 2013-11-24_18_12_88 However, using the following code: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd_hh_mm_ss"]; NSString *dateString = [dateFormatter stringFromDate:[NSDate date]]; I get this date string instead: 2013-11-24_18:12:88 How can I force the dateFormatter to not delete...

How remove some special words from a string content?

I have some strings containing code for emoji icons, like :grinning:, :kissing_heart:, or :bouquet:. I'd like to process them to remove the emoji codes. For example, given: Hello:grinning: , how are you?:kissing_heart: Are you fine?:bouquet: I want to get this: Hello , how are you? Are you fine? I know...

Format floating point number with leading zeros [duplicate]

This question already has an answer here: printf how to do floating points with leading zeros 3 answers Why does System.out.format("%03.3f", 1.23456789); print 1.235 instead of 001.235? How has my format string to look like to get 001.235 as output of the following code line? System.out.format(format, 1.23456789); ...

Cannot Build/Run VisualD Console Example

I installed Visual D a few minutes ago(I wanted to give the language a test drive) and, using the built-in console example, tried to build and run it. Here is the code that Visual Studio generated for me: import std.stdio; int main(string[] argv) { writeln("Hello D-World!"); return 0; } And...

When parsing datetime into month day with English culture, it is still parsed in Turkish language

Here is the code. I still get incorrect results string srRegisterDate = "25.07.2009 00:00:00" CultureInfo culture = new CultureInfo("en-US"); srRegisterDate = String.Format("{0:dddd, MMMM d, yyyy}", Convert.ToDateTime(srRegisterDate), culture); The result is Cumartesi, Temmuz 25, 2009 Instead it should be Saturday, July 25, 2009 How can i fix this error? v4.5.2...

separate a string 2 by 2 using Python3 macadress format

i want to use a function like "{}".format (variable) so i can transform a string like: " A1B345FS " And i want to have something like: " A1:B3:45:FS " i am not able to use a while or a for. Can i use .join (variable) ????...

Format string with trailing zeros removed for x decimal places in Swift [duplicate]

This question already has an answer here: Formatting decimal places with unknown number 3 answers This in Swift (1.2) let doubleValue1 = Double(10.116983123) println(String(format: "%.2f", doubleValue1)) let doubleValue2 = Double(10.0) println(String(format: "%.2f", doubleValue2)) Prints 10.12 10.00 I'm looking for a way using a formatter or a direct string format...

Error in Defining an associative array in D

So I would like to implement a hash lookup for translating codons to amino acids in D. When i write int[string] codon_table = [ "ATG": 'M', "TTT": 'F', "TTC": 'F', "TTA": 'L', "TTG": 'L', "CTT": 'L', "CTC": 'L', "CTA": 'L', "CTG": 'L', "ATT": 'I', "ATC": 'I', "ATA": 'I', "GTT": 'V',...

Javascript: something like string.format with property names

I wanted to make a method that i could pass a recordset (could just as easily be an general object) with format string to replace values by name. I found this other answer on SO that almost did it: function format(str, obj) { return str.replace(/\{\s*([^}\s]+)\s*\}/g, function(m, p1, offset, string)...

In D, how can I declare a hash of immutable types that is itself mutable?

I believe I was able to do this in an earlier version of the language, and indeed, code I wrote several months ago, which compiled fine then, does not compile now. Example: immutable(X)[int] myhash; myhash[5] = some_immutable_X; //previously fine. myhash[5] = some_other_immutable_X; //previously fine also. Now however, dmd complains with...

Python: '{:,}'.format() why is this working?

There is a kata in codewars where the task is to write a function that takes an integer in input and outputs a string with currency format. For example 123456 -> "123,456". I had a solution, but it was much uglier than this one with string formatting: def to_currency(price): return...