String formatting with *args - python

I looked at the following few posts and wasn't quite able to figure out what I want to do.
python - How to format variable number of arguments into a string?
Pass *args to string.format in Python?
What I want to do is simple. Given some array of variable length I want to be able to print all the arguments individually. That is, I want
print('{} {} ...'.format(*arg))
Obviously I won't be able to predict how many {} I will need before hand and I tried len(x)*'{}' which didn't yield what I wanted. If I leave that out then I only get the first argument. What is the way to achieve this?

so why not just:
print(" ".join(map(str,args)))
which does the same thing as {} {} ... in format

Why use a format string at all? print can do this for you:
print(*arg)

Related

Python string formatting when already "{}" in the string

I would like to know how could I format this string:
"){e<=2}"
This string is inside a function, so I would like to asign the number to a function parameter to change it whenever I want.
I tried:
"){e<={0}}".format(number)
But it is not working,
Could anybody give me some advice?
Thanks in advance
Double the braces which do not correspond to the format placeholder...
"){{e<={0}}}".format(number)
You could also use an f-string, if using Python 3.6 or above.
f"){{e<={number}}}"
An old-school version for this:
"){e<=%d}" % (number)
'){e<=2}'

String manipulation using list comprehension

I am trying below code and expecting output as,
matching string where every even letter is uppercase, and every odd letter is lowercase, however my output is list of all uppercase characters.
def myfunc(*args):
return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
How can I get expected output ? I tried same list comprehension syntax to test and it works fine. What's wrong with this specific code ?
By writing *args in your function declaration, it means that you're iterating over a number of strings and not just one string. For example:
myfunc('hello', 'goodbye')
Your function will iterate over a hello and goodbye, with hello having an index of 0 which is even number and thus converting its characters to uppercase, whereas goodbye has an index of 1 which is odd and thus covnerting its characters to lowercase:
HELLOgoodbye
If you wish to call your function for only one string, you have to remove the * from *args or inserting the string's characters one by one:
myfunc('h','e','l','l','o')
So, the declaration and implementation of your function should look like this:
def myfunc(args):
return ''.join([args[i].upper() if i%2==0 else args[i].lower() for i in range(len(args))])
Calling myfunc('hello') will return the correct result.
The problem is, you're using var-args. That's wrapping the string passed with a list, then you're iterating over that list (which only contains one string). This means your code does work to some extent; its just alternating the case of each whole word instead of each character.
Just get rid of the var-args:
def myfunc(word):
return ''.join([word[i].upper() if i%2==0 else word[i].lower() for i in range(len(word))])
print(myfunc("hello world"))
# HeLlo WoRlD
I'll just note, there's a few ways this could have been debugged. If you had checked the contents of args, you would have seen that it only contained a single element when one argument was passed, and two when two arguments were passed. If you had passed two arguments in, you would have also noticed that it alternated the case of each word as a whole. That would have likely given you enough hints to figure it out.
The above answers are correct but they ask you to modify the current syntax. In general you should try to understand how *args works.
In python, *args in a function definition is used to receive variable number of arguments. Such cases arise when we don't know in advance how many arguments will be passed.
For example :
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Now coming back to your code, you can make it run by selecting the first argument from the args list. See below :
def myfunc(*args):
return ''.join([args[0][i].upper() if i%2==0 else args[0][i].lower() for i in range(len(args[0]))])
print(myfunc("input"))
Help the community by selecting the best answer for this question.

Python Format Best Practices

I'm just coming up to speed with Python and had a question about best practices (or at least common practices) around using .format on a string.
My question is mostly around when you would use blank curly brackets vs. an index number vs. a name.
For example if you had a single variable that you wanted to include in a string which one would you do?
print "I {} Stack Overflow".format(var)
print "I {0} Stack Overflow".format(var)
print "I {verb} Stack Overflow".format(verb = var)
Does this change if you have multiple variables you want to include? Maybe it's OK to include {} for a single var, but never for multiple vars?
Any thoughts or insights here would be greatly appreciated.
Thanks!
I don't think there are (yet) any practices established as "best" or even as "common", so you'll get a bunch of opinions (including mine:-).
I think that {named} curlies are the way to go when your format string is a variable (e.g coming from a database or config file, picked depending on user's chosen language, etc, etc) because they let you pick and choose which of the (named) arguments to format, the order, possibly repeat them, and so forth, while staying readable.
If the format string is a literal, empty curlies a la {} are least obtrusive and thus may end up most readable -- unless your format string has "too many" of them, which of course is a style judgment.
At least it's a style issue very cognate to the one you face every time you define or call a function -- how any positional arguments or parameters are "too many" for readability, should you go whole hogs to named parameters and arguments only, etc, etc. Similar considerations apply!
print " I {} Stack Overflow.".format(var) is the correct way.
If you need multiple variable you would just place more curly brackets and add the var names separated by a comma.
print "I {} Stack Overflow. It is a great {} {}!".format(var, var1, var3)
I know this is an old question, but Python 3.6 brings a very cool string format, called "f-strings". It's similar to Javascript. Here is an simple example:
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
It only works in Python 3.6 and above, but I think it's the easiest and more readable way to format strings in Python.
It's ok to use empty braces for one or two variables. I would recommend using named replacement:
for more variables
in situations where replaced string is hard to read
when injected var is repeated.

Python print skip arguments

I have this dirty short line of code printing a formatted date:
print '%f %d' % math.modf(time.time())
Now the modf method gives back two arguments, so the print function expects both. In the sake of purely doing this, and not the simple alternative of putting the output separately in a variable; is there any existing way of excepting parameters in print or is there any way to call specific argument-indexes?
For example I have 3 arguments in a print:
print '%s %d.%f' % 'Money',19,.99
I want to skip the first String-parameter that is parsed. Is there any way to do this?
This is mainly a want-to-know-if-possible question, no need to give alternative solutions :P.
Not in "old school" string formatting.
But the format method of strings does have this ability.
print "{1}".format ("1","2")
The above will skip the "1" and will only print "2".
I hope you don't mind I gave an alternative despite you not asking for it :)

Python, string (consisting of variable and strings, concatenated) used as new variable name?

I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that has an index (from another variable).. I simplified my code below to just show the relevant parts its part of a macro that is replacing values:
toreplacetype = 'type'
toreplace_indx = 5
replacement_string = 'list'+toreplacetype[toreplace_indx]
so... I am trying to make the string on the last line equal to the actual variable name:
replacement_string = listtype[5]
Any advice on how to do this is appreciated
EDIT:
To explain further, this is for a macro that is sort of a template system where I am indicating things in a python script that I want to replace with specific values so I am using regex to do this. So, when I match something, I want to be able to replace it from a specific value within a list, but, for example, in the template I have {{type}}, so I extract this, but then I need to manipulate it as above so that I can use the extracted value "type" to call a specific value from within a list (such as from a list called "listtype") (there is more than 1 list so I need to find the one called "listtype" so I just want to concatenate as above to get this, based on the value I extracted using regex
This is not recommended. Use a dict instead.
vars['list%s' % toreplacetype][5] = ...
Hrm...
globals()['list%s'% toreplacetype][toreplace_indx]
replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']'
will yield listtype[5] when you print it.
You need to basically break it into 5 parts: 1 string variable, 3 strings and an int casted to a string.
I think this is what you are asking?

Categories

Resources