How to make string f-string after variable initiazation? [duplicate] - python

This question already has answers here:
How to postpone/defer the evaluation of f-strings?
(14 answers)
Closed 3 years ago.
Let's suppose I get some string and set it to variable - it can't be created as f-string:
str1 = 'date time for {val1} and {val2}'
Then variables inside the string initialized:
val1 = 1
val2 = 77
Calling print(str1) will return 'date time for {val1} and {val2}'. But I would like to get
'date time for 1 and 77'
Is there any function to make a string as a F string? So I want to call something make_F(str1) and get f-string
PS I cant use dict {'val1':1, 'val2':77} with .format because don't know which variables will be needed in the string. I just want magic happen with F-string.

You need:
str1 = 'date time for {val1} and {val2}'
val1 = 1
val2 = 77
print(eval(f"f'{str1}'"))

You first need to describe variables as e.g
var1 = None
var2 = None
Then you can use it with f-string like this:
x = f'print {var1} and {var2}'
print(x)
And thats it, you will get the result.

Related

Python string format template for selected parameters [duplicate]

This question already has answers here:
partial string formatting
(23 answers)
Closed 7 months ago.
I want to create a string template that only selected parameters gets value in each session.
For example:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much"
s.format(fruits_num=fruits_num, fruit_name='apple')
s.format(fruits_num=fruits_num, fruit_name='orange')
I want to avoid the repeated assignment of fruits_num=fruits_num
In a pseduo code:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much".format(fruits_num=fruits_num)
s.format(fruit_name='apple')
s.format(fruit_name='orange')
I this possible? Thanks.
You can double the { around fruits_name so that it will be literal, which will keep it until the next call to .format().
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {{fruit_name}} very much".format(fruits_num=fruits_num)
print(s.format(fruit_name='apple'))
print(s.format(fruit_name='orange'))

How create variable name with other variable's value in it? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed last year.
a = "Jack"
b = "Sam"
Now I want some way to create this:
c_{b value} = 10
That means:
c_Jack = 10
And the following:
c_{a value} = 20
That means:
c_Sam = 20
This is actually a bad practice to do this. You better to use a dict.
BTW, you can do this:
In [3]: a = "Jack"
In [4]: exec(f'c_{a} = 10')
In [5]: c_Jack
Out[5]: 10

Python incrementally set a variable to equal another variable [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am attempting to set the value of a variable to incrementally equal that of another variable based on the iteration of the loop I am on.
I have the following code:
no_keywords=3
cat_0='Alpha'
cat_1='Bravo'
cat_2='Charlie'
cat_3='Delta'
for _ in range(no_keywords):
keyword1 = exec(f'cat_{_}')
print(keyword1)
However the printed value just returns a NoneType object. I would like the value of Keyword1 to take on the value of the cat_ variable based on the iteration of loop I am on.
Please can somebody help in explaining in what I am doing wrong and help me recitfy?
Thanks,
D
Try this:
no_keywords = 3
cat_0 = 'Alpha'
cat_1 = 'Bravo'
cat_2 = 'Charlie'
cat_3 = 'Delta'
for _ in range(no_keywords):
keyword1 = None
exec(f'keyword1 = cat_{_}')
print(keyword1)
Seems like exec does not return a value, but you can set your variable within the command passed to it.

How to use a variable as a dictionary key? [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 3 years ago.
coming_monday = today + datetime.timedelta(days=-today.weekday(), weeks=1)
month = coming_monday.strftime("%B")
collection = db['empmain']
record = collection.find_one({'Availablity.<want to pass in the month variable here'})
format of the collection:
enter image description here
This example worked for me:
a = 1
b = 2
c = 3
mydict = {a : "a_", b : "b_", c : "c_"}
I've declard some variables with some values as above.
>>> mydict[1]
'a_'
>>> mydict[b]
'b_'
I was able to access values in the dictionary using both the variable names or the values.

taking a string from a python list and using it to update a variable of the same name? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 years ago.
I'm trying to make python take a string from a list at random and then use that string to determine what variable of the same name to add 1 to. I can't use a dictionary because of how I'm using the variables in other modules.
This is what I have for an example:
import random
item1 = 0
item2 = 0
item3 = 0
items = ("Item1","Item2","Item3")
item = random.choice(items)
#I want it to find the variable of the same name and then add 1 to said variable
#depending on what item is chosen to be "item".
As the comments already mentioned, please don't do that, it's bad practice. You should change the code in your other modules to look for the dictionary, rather than those variables.
But if you really have to, this code goes where your comments are:
exec(item.lower() + ' += 1')
If you can't use dictionary, one option is to use locals setattr:
import random
item1 = 0
item2 = 0
item3 = 0
items = ("Item1","Item2","Item3")
item = random.choice(items)
locals()[item.lower()] += 1
What you could do instead is using a dictionary (associative container) : It works with a key->value system.
Here, the name of your variable will be the key, and the number it holds will be the value.
Something like :
dict = {'Item1': 0, 'Item2': 0, 'Item3': 0}
item = random.choice(dict.keys())
Hope it helps.

Categories