Python string format template for selected parameters [duplicate] - python

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'))

Related

Create Variable Name When Defining A Function [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am working in Python trying to write a function using a list of variables.
Here is the data I am working with:
material_list=['leather', 'canvas', 'nylon']
def materialz(MAT):
MAT=support.loc[(material==MAT)].sum()
for i in enumerate(material_list):
materialz(i)
What I am looking for is to pass in each of the items in the list to the function to produce global variables.
leather=
canvas=
nylon=
Any help would be appreciated!
You could create a dictionary and dynamically assign the key-value pairs there. Such as:
material_list=['leather', 'canvas', 'nylon']
material_dict={}
for i in enumerate(material_list):
material_dict[i]=value #Where i would be the key and value the value in the key-value pair
you can use exec
var = 'hello'
output = hello
exec('var = "world"')
print(var)
output = world

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])

How can I dynamically create a name of a variable in Python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I am having a function in python
def func(dataFrame,country,sex):
varible_name=dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
Now, for example, I call this function
func(dataFrame,'England','M')
I want that variable name be England_M instead of variable_name.
You can't do that in Python.
What you can do instead is store the results under a dictionary with key = England_M for instance.
In your case, you could do the following :
def func(dataFrame,country,sex):
tmp = dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
variable_name = "{c}_{s}".format(c=country, s=sex)
return dict(variable_name=tmp)
Now using it :
results = func(dataFrame, "England", "M")
print(results['England_M'])

Getting key arguments from prepared string [duplicate]

This question already has answers here:
Get keys from template
(7 answers)
Closed 5 years ago.
I have a prepared string, e.g. my_string = 'My name is {name}.'
and I have dictionary of kwargs, such as:
format_kwargs = {
'name': 'John',
...
}
So that I can format the string in this manner: my_string.format(**format_kwargs)
That is all good. The problem is that I want to determine what keys are in the string, so that I do not calculate the kwargs needlessly. That is, I have a set of keywords used in these strings by default, but not all of them are used in all strings. They are basically regular messages shown to user, such as '{name}, you account was successfully created!'.
I want to do something like:
format_kwargs = {}
if 'name' in <my_string.keys>:
format_kwargs['name'] = self.get_user().name
if '...' in <my_string.keys>:
format_kwargs['...'] = some_method_...()
my_string.format(**format_kwargs)
How do I retrieve the keys?
EDIT:
a simple if 'name' in my_string does not work because that would also match something like {parent_name} or 'The name change was not successful.'
Use string.Formatter
from string import Formatter
s = 'Hello {name}. Are you {debil_status}'
keys = [i[1] for i in Formatter().parse(s)]
print keys
>>> ['name', 'debil_status']

Python unpack list for use in formatted string [duplicate]

This question already has answers here:
Pythonic way to print list items
(13 answers)
Closed 3 years ago.
I have a string that I am dynamically creating based off user input. I am using the .format function in Python to add a list into the string, but I would like to remove the quotes and brackets when printing.
I have tried:
return (('{} is {}x effective against {}').format(opponentType, overallHitMultiplier, [str(x) for x in playerTypes]))
and
return return (('{} is {}x effective against {}').format(opponentType, overallHitMultiplier, playerTypes))
which both return a string that looks like this:
fighting is 2x effective against ['normal', 'ghost']
but I would like it to return something like:
fighting is 2x effective against normal, ghost
The length of the list is variable so I can't just insert the list elements one by one.
Here is a more complete response:
def convert_player_types_to_str(player_types):
n = len(player_types)
if not n:
return ''
if n == 1:
return player_types[0]
return ', '.join(player_types[:-1]) + f' and {player_types[-1]}'
>>> convert_player_types_to_str(['normal'])
'normal'
>>> convert_player_types_to_str(['normal', 'ghost'])
'normal and ghost'
>>> convert_player_types_to_str(['normal', 'ghost', 'goblin'])
'normal, ghost and goblin'

Categories