Python: f-string in a variable from another function [duplicate] - python

This question already has answers here:
How to postpone/defer the evaluation of f-strings?
(14 answers)
Closed yesterday.
This post was edited and submitted for review yesterday.
I have some variables, some of them came from another functions:
dogs = calculate_dogs()
name = random_owner()
city = gps_position()
sentence = '{name} has {dogs} dog(s) and lives in {city}'
To print, I would normally add one f like this:
print(f'{name} has {dogs} dog(s) and lives in {city}')
But since this variable called sentence comes "as is" from somewhere else, what can I do to print it (or anything else)?
I first tried this, unsuccessfully:
print(f'{sentence}')
For now I made a kinda nasty workaround like this:
sentence = sentence.replace('{name}', name)
sentence = sentence.replace('{dog}', dog)
sentence = sentence.replace('{city}', city)
print(sentence)
Any ideas?
Edited question: Since the variables are coming from different sources, it doesn't seem to work a dictionary, or I just don't do it right.
I tried:
variables = {'dogs' : calculate_dogs(), 'name' : random_owner(), 'city' : gps_position()}

You can call str.format and pass the variable values as keyword arguments.
sentence = '{name} has {dogs} dog(s) and lives in {city}'
variables = {'dogs' : 1, 'name' : 'Bob', 'city' : 'LA'}
print(sentence.format(**variables))

Related

What does format() in Python actually do?

I'm coming into Python3 after spending time with Ruby, R, and some Java. Immediately I've come across the format() function and I'm a little lost as to what it does. I've read Python | format() function and see that it somehow resembles this in ruby:
my_name = "Melanie"
puts "My name is #{my_name}."
Outputs:
"My name is Melanie."
However, I don't understand why I can't just use a variable as above. I must be very much misunderstanding the usage of the format() function. (I'm a novice, please be gentle.)
So what does format() actually do?
You can definitely use a variable in the string example that you have shown, in the following manner:
my_name = "Melanie"
Output = "My name is " + my_name + "."
print(Output)
My name is Melanie.
This is the easy way, but not the most elegant.
In the above example, I have used 3 lines and created 2 variables (my_name and Output)
However, I can get the same output using just one line of code and without creating any variables, using format()
print("My name is {}.".format("Melanie"))
My name is Melanie.
Curly braces {} are used as placeholders, and the value we wish to put in the placeholders are passed as parameters into the format function.
If you have more than one placeholder in the string, python will replace the placeholders by values, in order.
Just make sure that the number of values passed as parameters to format(), is equal to the number of placeholders created in the string.
For example:
print("My name is {}, and I am {}.".format("Melanie",26))
My name is Melanie, and I am 26.
There are 3 different ways to specify placeholders and their values:
Type 1:
print("My name is {name}, and I am {age}.".format(name="Melanie", age=26))
Type 2:
print("My name is {0}, and I am {1}.".format("Melanie",26))
Type 3:
print("My name is {}, and I am {}.".format("Melanie",26))
Additionally, by using format() instead of a variable, you can:
Specify the data type, and
Add a formatting type to format the result.
For example:
print("{0:^7} has completed {1:.3f} percent of task {2}".format("Melanie",75.765367,1))
Melanie has completed 75.765 percent of task 1.
I have set the data type for the percentage field to be a float, with 3 decimals, and given a character length of 7 to the name, and center-aligned it.
The alignment codes are:
' < ' :left-align text
' ^ ' :center text
' > ' :right-align
The format() method is helpful when you have multiple substitutions and formattings to perform on a string.
The format function is a method for string in python, it is use to add a variable to string. for example:
greetings = 'hello {0}'
visitor = input('please enter your name')
print(greetings.format(visitor))
it can also be use to pad/position string also, thisn actually align the visitor into to the greetings in 10 byte of space
greetings = 'hello {0:^10}'
visitor = input('please enter your name')
print(greetings.format(visitor))
Also, there are two type of format in python 3x: the format expression and the format function.
the format expression is actually this '%'
and many more on 'format'. Maybe you should check on the doc 'format' by typing "help(''.format)"
An example using the format function is this:
name = Arnold
age = 5
print("{ }, { }".format(name, age))
This displays:
Arnold, 5

Adding different elements to the list with conditions Python - return a tuple [duplicate]

This question already has answers here:
Python — check if a string contains Cyrillic characters
(4 answers)
Closed 3 years ago.
I have a task to write a function that adds "Hello, " and "Привет" if a name in the list is English or Russian and then returns a tuple. For example, we have ["Mary", "Kate", "Маша", "Alex"]. Our function should return a tuple like this: ('Hello, Mary', 'Hello, Kate', 'Привет, Маша', 'Hello, Alex). I have no idea how to achieve this. I can add Hello to all elements, but what to do with this Привет I don't know.
What I came up with so far...
Please help!
def name(my_list):
for x in my_list:
new_lis = ["Hello, " + x for x in my_list]
new_lis1 = tuple(new_lis)
print(new_lis1)
name(my_list)
this isn't really the type of website, were you post your question and someone else finds the answer for you - but you are in luck, and someone had the exact same question before.
Following the answers in the linked thread, you could do something like:
def salutation_name(name):
if all([c in '[а-яА-Я]' for c in name]):
return f'Привет {name}'
else:
return f'Hello {name}'
names = ["Mary", "Kate", "Маша", "Alex"]
print([salutation_name(name) for name in names])

Function call does not execute its definition [duplicate]

This question already has answers here:
My variable is defined but python is saying it isn't?
(2 answers)
Closed 4 years ago.
I seek advice on a matter relating to this function.
I have tried various editing and indentation on the code, but it is showing the same result.
It shows NameError: name 'sentence' is not defined although I have defined it in the function.
The code is:
def about (name, age, likes):
sentence = "Meet {}, he is {} years old and likes {}".format(name,age,likes)
return sentence
about ("Jack", 23, "programming")
print (sentence)
You should call function and assign it to an variable:
def about(name, age, likes):
sentence = "Meet {}, he is {} years old and likes {}".format(name,age,likes)
return sentence
Then
val = about("Jack", 23, "programming")
print(val)
you can also use sentence instead of val but this will not be the same sentence in function scope.
try this now....
def about (name, age, likes):
sentence = "Meet {}, he is {} years old and likes {}".format(name,age,likes)
return sentence
print(about('rohit',23,'programming'))
sentense scope is bounded to about function... and trying to print it out of the function scope may not work.

Accessing a variable's name [duplicate]

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 4 months ago.
I'm trying to access a variable's name. For example, if I call a function to print a list (printL)
and want to print my list's name "A_minus_B":
def printL (xlist):
print "****************************"
print "name of list"
print (" entries : "),len(xlist)
print xlist
print "****************************"
return()
How can I get the function to print "A_minus_B" instead of "name of list", the name I used when calling the function printL(A_minus_B)?
You can't.* The detailed reasons are discussed in the Python language reference, but basically what Python does when you call printL(A_minus_B) is take the value that has been labeled A_minus_B and create a new label, xlist, that happens to refer to the same thing. From that point on, the label xlist has absolutely no connection to the other label A_minus_B, and in fact, the value which has been labeled A_minus_B or xlist or whatever has no connection to any of the names that have been used to label it.
*Well, you can, by using some deep "Python voodoo"... you would basically have to tell Python to read the piece of source code where you call printL(A_minus_B) and extract the variable name from there. Normally that's the kind of thing you probably shouldn't be doing (not because you're a beginner, but because it usually indicates you've designed your program the wrong way), but debugging is one of those cases where it's probably appropriate. Here's one way to do it:
import inspect, pprint
def print_values(*names):
caller = inspect.stack()[1][0]
for name in names:
if name in caller.f_locals:
value = caller.f_locals[name]
elif name in caller.f_globals:
value = caller.f_globals[name]
else:
print 'no such variable: ' + name
# do whatever you want with name and value, for example:
print "****************************"
print name
print (" entries : "),len(value)
print value
print "****************************"
The catch is that when you call this function, you have to pass it the name of the variable you want printed, not the variable itself. So you would call print_values('A_minus_B'), not print_values(A_minus_B). You can pass multiple names to have them all printed out, for example print_values('A_minus_B', 'C_minus_D', 'foo').
Alternate way to do it:
list_dict = {} #creates empty dictionary
list_dict['list_a'] = [1,2,3,4,5,6] # here you create the name (key)
nice_name = 'list_b'
list_dict[nice_name] = [7,8,9,10,11,12] # here you use already existing string as name (key)
def list_info(ld):
for key in sorted(ld):
print "****************************"
print key
print " entries : " ,len(ld[key])
print ld[key]
print "****************************"
list_info(list_dict)

Use a string to call function in Python [duplicate]

This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 9 years ago.
Some days ago I was searching on the net and I found an interesting article about python dictionaries. It was about using the keys in the dictionary to call a function. In that article the author has defined some functions, and then a dictionary with key exactly same as the function name. Then he could get an input parameter from user and call the same method (something like implementing case break)
After that I realised about the same thing but somehow different. I want to know how I can implement this.
If I have a function:
def fullName( name = "noName", family = "noFamily" ):
return name += family
And now if I have a string like this:
myString = "fullName( name = 'Joe', family = 'Brand' )"
Is there a way to execute this query and get a result: JoeBrand
For example something I remember is that we might give a string to exec() statement and it does it for us. But I’m not sure about this special case, and also I do not know the efficient way in Python. And also I will be so grateful to help me how to handle that functions return value, for example in my case how can I print the full name returned by that function?
This does not exactly answer your question, but maybe it helps nevertheless:
As mentioned, eval should be avoided if possible. A better way imo is to use dictionary unpacking. This is also very dynamic and less error prone.
Example:
def fullName(name = "noName", family = "noFamily"):
return name + family
functionList = {'fullName': fullName}
function = 'fullName'
parameters = {'name': 'Foo', 'family': 'Bar'}
print functionList[function](**parameters)
# prints FooBar
parameters = {'name': 'Foo'}
print functionList[function](**parameters)
# prints FoonoFamily
You could use eval():
myString = "fullName( name = 'Joe', family = 'Brand' )"
result = eval(myString)
Beware though, eval() is considered evil by many people.
I know this question is rather old, but you could do something like this:
argsdict = {'name': 'Joe', 'family': 'Brand'}
globals()['fullName'](**argsdict)
argsdict is a dictionary of argument, globals calls the function using a string, and ** expands the dictionary to a parameter list. Much cleaner than eval. The only trouble lies in splitting up the string. A (very messy) solution:
example = 'fullName(name=\'Joe\',family=\'Brand\')'
# Split at left parenthesis
funcname, argsstr = example.split('(')
# Split the parameters
argsindex = argsstr.split(',')
# Create an empty dictionary
argsdict = dict()
# Remove the closing parenthesis
# Could probably be done better with re...
argsindex[-1] = argsindex[-1].replace(')', '')
for item in argsindex:
# Separate the parameter name and value
argname, argvalue = item.split('=')
# Add it to the dictionary
argsdict.update({argname: argvalue})
# Call our function
globals()[funcname](**argsdict)

Categories