Building a string using symbols - c++

In python, I'm able to build a string using this method:
>>> s = "%s is my name" %("Joe")
>>> s
'Joe is my name'
Is there a similar way to do this in C++? I know C has
printf("%s is my name", "Joe")
But that's for printing to standard out. Ideally I'd like something like the Python example. Thanks!
EDIT: Is there a name for this kind of thing? I couldn't think of what to google!

The sprintf command works like printf, but has an extra parameter at the front. The first parameter is an array of characters of where to store the string instead of printing it.
char chararray[1000];
sprintf(chararray,"%s is my name","Joe");
http://www.cplusplus.com/reference/cstdio/sprintf/

Related

From SAS to Python : substr

I would like to use the function substr(my_var,1,2) of SAS in Python. I tried a lot of functions like contains(), split() but it didn't work.
The functions contains() and split() work only for a string value. I would like to use it on a Python Series without using a for.
Thanks a lot for your help
A string in python can be sliced like any list:
>>> str = 'Hello World'
>>> str[1:3]
'el'
>>> str[1:-2]
'ello Wor'
To get substrings for multiple strings, you can use list comprehensions:
>>> strs = ['Hello World', 'Foobar']
>>> [ str[1:4] for str in strs]
['ell', 'oob']
In python, you may try this:
my_var[1:3]
This gets sub string of my_var from position 1 to 3 (exclusive).

Printing Values from a list without spaces in python 2.7

Suppose I have a list like
list1 = ['A','B','1','2']
When i print it out I want the output as
AB12
And not
A B 1 2
So far I have tried
(a)print list1,
(b)for i in list1:
print i,
(c)for i in list1:
print "%s", %i
But none seem to work.
Can anyone suggest an alternate method
Thank you.
From your comments on #jftuga answer, I guess that the input you provided is not the one you're testing with. You have mixed contents in your list.
My answer will fix it for you:
lst = ['A','B',1,2]
print("".join([str(x) for x in lst]))
or
print("".join(map(str,lst)))
I'm not just joining the items since not all of them are strings, but I'm converting them to strings first, all in a nice generator comprehension which causes no memory overhead.
Works for lists with only strings in them too of course (there's no overhead to convert to str if already a str, even if I believed otherwise on my first version of that answer: Should I avoid converting to a string if a value is already a string?)
Try this:
a = "".join(list1)
print(a)
This will give you: AB12
Also, since list is a built-in Python class, do not use it as a variable name.

Bug (??) in formatting long values with CString::Format

I have issues with the following code:
CString cstr;
cstr.Format("SELECT foobar %ld, %ld ",
" AND type = '%s' ",
1426233870,1426243870, "'OR'");
The resulting CString contains wrong numbers!
The code is simplified, actually I am selecting datasets from a database between two timestamps in seconds.
I was able to solve my problem by formatting two Strings and appending the second at the end of the first, so I do not need an answer. But if sombody could confirm that this is a bug in CString::Format, this may preserve other people from loosing as many nerves as I did ...
best regards
If this is MFC, it should be like this:
CString cstr;
cstr.Format("SELECT 123=%ld, 456=%ld AND type = '%s' ", 123, 456, "'type'");
It's like printf.

Boost program options with default value

I have a console application in c++ using boost program_options.
I have a parameter named --list-timezones
now I want to use it like that
either
myapp --list-timezones
which gives me all available timzones
or
myapp --list-timezones AT
which gives me onle the timezones for Austria
My options inializitation is the following
options.add_options()
("date-format,d", po::value<string>()->value_name("<Formatstring>")->default_value("%Y-%m-%d %H:%M:%S","\"%Y-%m-%d %H:%M:%S\""),"Format-string for input or output\ne.g. \"%Y-%m-%d %H:%M:%S\"")
("input-format,i", po::value<string>()->value_name("<Representation>")->default_value("HEX"),"HEX hex value\nBIN binary value\nDEC decimal value")
("output-format,o", po::value<string>()->value_name("<Representation>")->default_value("HEX"),"HEX hex Value\nBIN binary value\nDEC decimal value")
("to,t", po::value<string>()->value_name("<Date-Format>"),"CHROME\nMAC\nUNIX\nUNIX_ms\nWin64\nWinCookie\nWinOle\nWinFiletime\nDOS\nHFS\nHFS+")
("from,f", po::value<string>()->value_name("<Date-Format>")/*->default_value("UNKNOWN")*/,"CHROME\nMAC\nUNIX\nUNIX_ms\nWin64\nWinCookie\nWinOle\nWinFiletime\nDOS\nHFS\nHFS+\nUNKNOWN")
("timezone,z", po::value<string>()->value_name("<Time-Zone>")->default_value("UTC"),"e.g \"Europe/Vienna\"\n execute '--list-timezones ALL' to see all available timezones")
("list-timezones,l", po::value<string>()->value_name("<ISO-3166 Country Code>"), "List all available timezones\nyou can filter with ISO3166 country code(e.g AT for Austria)")
("value,v", po::value<string>()->value_name("<value>"), "Input Value")
("swap-bytes,s", "Swap bytes of result")
;
Any ideas how I can handle that?
If I use --list-timezones without an parameter I get an Exception
Thanks
florian
You want this:
("list-timezones,l", po::value<string>()->implicit_value("")->value_name(...
Then you'll be able to give an argument or not. If none is given, the string value will be empty, which seems like a reasonable sentinel value in your case.

wxString: Is there any C/C++ code that implements string formatting using Python3-like placeholders? [duplicate]

This question already has answers here:
How to construct a std::string with embedded values, i.e. "string interpolation"?
(8 answers)
Closed 2 years ago.
I am rewriting our application using wxWidgets. One of the goals is to replace our old approach to the localized strings. Another possible goal is to embed the Python interpreter to the application -- but only later. Anyway, it would be nice any C/C++ code or library capable of Python-like string formatting that uses the curly braces.
If you do not know Python, here is the doc for its format function. You can find the reference to the Format Specification Mini-Language inside, and the Format examples. Some extract from the doc... (The >>> is a prompt of the interactive Python mode, the line below shows the result of the call. Python uses single or double quotes as a string delimiter):
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
'abracadabra'
I would also like to use the Python formatting with the named placeholders (instead of numeric indices). In Python, the str.format_map(mapping) method of strings is used where the mapping is of the map<string, some_type> like type. Say, my_dictionary contains mapping like:
"name" --> "Guido"
"country" --> "Netherlands"
Having a template string like below, I would like to get the result...
wxString template("{name} was born in {country}.");
wxString result(format_map(s, my_dictionary));
// the result should contain...
// "Guido was born in Netherlands."
Do you know any avaliable C or C++ code capable of that, or do I have to write my own?
Thanks for your time and experience,
Petr
Yes. The fmt library uses format string syntax based on Python's str.format. It supports most of the formatting options of str.format including named arguments. Here's an example:
std::string s = fmt::format("{0}{1}{0}", "abra", "cad");
// s == "abracadabra"
Disclaimer: I'm the author of this library.