string-formatting

Python: Logging TypeError: not all arguments converted during string formatting

让人想犯罪 __ 提交于 2019-11-27 15:33:48
问题 Here is what I am doing >>> import logging >>> logging.getLogger().setLevel(logging.INFO) >>> from datetime import date >>> date = date.today() >>> logging.info('date={}', date) Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 846, in emit msg = self.format(record) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 723, in format return fmt

Slicing strings in str.format

*爱你&永不变心* 提交于 2019-11-27 15:28:05
I want to achieve the following with str.format : x,y = 1234,5678 print str(x)[2:] + str(y)[:2] The only way I was able to do it was: print '{0}{1}'.format(str(x)[2:],str(y)[:2]) Now, this an example and what I really have is a long and messy string, and so I want to put slicing inside the {} . I've studied the docs , but I can't figure out the correct syntax. My question is: is it possible to slice strings inside a replacement field? Martijn Pieters No, you cannot apply slicing to strings inside a the replacement field. You'll need to refer to the Format Specification Mini-Language ; it

StringFormat and Multibinding with Label

跟風遠走 提交于 2019-11-27 15:27:38
问题 I would like to use StringFormat to do someting like this : <Label x:Name="myLabel"> <Label.Content> <Multibinding StringFormat="{}{0} - {1}"> <Binding Path="Lib1" /> <Binding Path="Lib2" /> </MultiBinding> </Label.Content> </Label> However, it's doesn't work and I got this error instead : MultiBinding failed because it has no valid Converter. MultiBindingExpression:target element is 'Label' (Name='myLabel'); target property is 'Content' (type 'Object') Is there any way to make this code work

How can I append a formatted string to an existing String?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 15:27:35
Using format! , I can create a String from a format string, but what if I already have a String that I'd like to append to? I would like to avoid allocating the second string just to copy it and throw away the allocation. let s = "hello ".to_string(); append!(s, "{}", 5); // Doesn't exist A close equivalent in C/C++ would be snprintf . I see now that String implements Write , so we can just use write! : use std::fmt::Write; pub fn main() { let mut a = "hello ".to_string(); write!(&mut a, "{}", 5).unwrap(); println!("{}", a); assert_eq!("hello 5", a); } ( Playground ) It is impossible for this

How to center a string using String.format?

谁说我不能喝 提交于 2019-11-27 15:04:02
public class Divers { public static void main(String args[]){ String format = "|%1$-10s|%2$-10s|%3$-20s|\n"; System.out.format(format, "FirstName", "Init.", "LastName"); System.out.format(format, "Real", "", "Gagnon"); System.out.format(format, "John", "D", "Doe"); String ex[] = { "John", "F.", "Kennedy" }; System.out.format(String.format(format, (Object[])ex)); } } output: |FirstName |Init. |LastName | |Real | |Gagnon | |John |D |Doe | |John |F. |Kennedy | I want the output to be centered. If I do not use '-' flag the output will be aligned to the right. I did not find a flag to center text

How do I customize output of a custom type using printf?

左心房为你撑大大i 提交于 2019-11-27 14:35:08
I've read through a good chunk of Expert F# and am working on building an actual application. While debugging, I've grown accustomed to passing fsi commands like this to make things legible in the repl window: fsi.AddPrinter(fun (x : myType) -> myType.ToString()) I would like to extend this to work with the printf formatter, so I could type e.g. printf "%A" instanceOfMyType and control the output for a custom type. The book implies that this can be done (p 93, "Generic structural formatting can be extended to work with any user-defined data types, a topic covered on the F# website"), but I

Leaving values blank if not passed in str.format

六眼飞鱼酱① 提交于 2019-11-27 14:20:24
I've run into a fairly simple issue that I can't come up with an elegant solution for. I'm creating a string using str.format in a function that is passed in a dict of substitutions to use for the format. I want to create the string and format it with the values if they're passed and leave them blank otherwise. Ex kwargs = {"name": "mark"} "My name is {name} and I'm really {adjective}.".format(**kwargs) should return "My name is mark and I'm really ." instead of throwing a KeyError (Which is what would happen if we don't do anything). Embarrassingly, I can't even come up with an inelegant

Right pad with zeros

情到浓时终转凉″ 提交于 2019-11-27 14:19:35
Sorry if this question was made already, I've made a deep search and nothing. Now, I know that: String.format("%05d", price); Will be padding my price with zeros to the left, so a price of 25 will result in 00025 What if I want to pad them to the right, so the result is 25000 ? How do I do that using only String.format patterns? Reimeus You could use: String.format("%-5s", price ).replace(' ', '0') Can I do this using only the format pattern? String.format uses Formatter.justify just like the String.printf method. From this post you will see that the output space is hard-coded, so using the

Format decimal value to string with leading spaces

穿精又带淫゛_ 提交于 2019-11-27 14:17:23
问题 How do I format a decimal value to a string with a single digit after the comma/dot and leading spaces for values less than 100? For example, a decimal value of 12.3456 should be output as " 12.3" with single leading space. 10.011 would be " 10.0" . 123.123 is "123.1" I'm looking for a solution, that works with standard/custom string formatting, i.e. decimal value = 12.345456; Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern. 回答1: This pattern {0,5:###.0} should work:

Nested f-strings

ⅰ亾dé卋堺 提交于 2019-11-27 14:16:13
Thanks to David Beazley's tweet , I've recently found out that the new Python 3.6 f-strings can also be nested: >>> price = 478.23 >>> f"{f'${price:0.2f}':*>20s}" '*************$478.23' Or: >>> x = 42 >>> f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-''' '-*+.42.+*-' While I am surprised that this is possible, I am missing on how practical is that, when would nesting f-strings be useful? What use cases can this cover? Note: The PEP itself does not mention nesting f-strings, but there is a specific test case . I don't think formatted string literals allowing nesting (by nesting, I take it to mean f'{f".."}