Replace word in string using f-string [duplicate] - python

This question already has answers here:
How to postpone/defer the evaluation of f-strings?
(14 answers)
Closed 2 years ago.
In Python, I'm trying to insert a variable into an imported string that already contains the variable name - as pythonically as possible.
Import:
x = "this is {replace}`s mess"
Goal:
y = add_name("Ben", x)
Is there a way to use f-string and lambda to accomplish this? Or do I need to write a function?

Better option to achieve this will be using str.format as:
>>> x = "this is {replace}`s mess"
>>> x.format(replace="Ben")
'this is Ben`s mess'
However if it is must for you to use f-string, then:
Declare "Ben" to variable named replace, and
Declare x with f-string syntax
Note: Step 1 must be before Step 2 in order to make it work. For example:
>>> replace = "Ben"
>>> x = f"this is {replace}`s mess"
# ^ for making it f-string
>>> x
'this is Ben`s mess' # {replace} is replaced with "Ben"

Related

Obtaining a string version of the variable name in Python [duplicate]

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 1 year ago.
Consider the following code:
x,y = 0,1
for i in [x,y]:
print(i) # will print 0,1
Suppose I wanted instead to print:
x=0
y=1
I realise f-strings can be used to print the intermediate variable name:
for i in [x,y]:
print(f"{i=}") # will print i=0, i=1
However, I am interested in the actual variable name.
There are other workarounds: using eval or using zip([x,y], ['x', 'y']), but I was wondering if an alternative approach exists.
I think this achieves what you want to do -
for i in vars():
print(f'{i}={vars()[i]}')

Not too sure about replace() function on Python - why isn't dog being replaced with cat? [duplicate]

This question already has answers here:
python: why does replace not work?
(2 answers)
Closed 1 year ago.
a = 'dog'
a.replace('dog', 'cat')
print (a)
Really basic question, the function seems to be fairly straightforward but it just isn't replacing in this instance for some reason - is it because replace doesn't inherently change "a"?
Yes, you are correct. It won’t modify a.
Replace function will return a replaced string.
So, if you like to replace the text in a. Use the below code.
a = 'dog'
a = a.replace('dog', 'cat')
print (a)
Strings are immutable data types in Python which means that its value cannot be updated. Variables can point at whatever they want.
str.replace() creates a copy of string with replacements applied. See documentation.
Need to assign a new variable for the replacement.
a = 'dog'
b = a.replace('dog', 'cat')
print(b)
Output:
cat

Variable inside python format specifier [duplicate]

This question already has an answer here:
How to pad numbers with variable substitution for padding width in format or f string? [duplicate]
(1 answer)
Closed 7 months ago.
I am wondering whether I can add a variable inside the f string to specify the width of item to be printed.
For example:
print("{:>5}".format("cat"))
In the example how can I replace 5 with a variable that can change at runtime.
inside the f string
Be careful using the term "f string" -- you're talking about a format string whereas an f-string is a feature of the latest releases of Python and something different, but related:
animal = 'cat'
pad = 5
print(f"{animal:>{pad}}")
Otherwise, if you just want a format string without the f-string, then #JohnnyMopp's comment (+1) shows the correct syntax.
Here is how:
a = 5
print("{:>"f"{a}""}".format("cat"))
Output:
cat
You can also do that using str.rjust():
a = 5
print("cat".rjust(a))
Output:
cat

How to add comma in print statement in Python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 5 years ago.
I'm new to python and learning how to code.
I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",".
Any idea how to separate it by comma?
I'm using Python 2.7
Include it in quotes, like this:
print str(list[-1]) + "," + str(sum)
Enclosing them in str() is unnecessary if list[-1] and sum are strings.
In general, symbols are interpreted as Python symbols (for example, names like sum are interpreted as variable or function names). So whenever you want to print anything as is, you need to enclose it in quotes, to tell Python to ignore its interpretation as a Python symbol. Hence print "sum" will print the word sum, rather than the value stored in a variable called sum.
You'll have to compose that together into a string. Depending on what version of Python you're using, you could either do:
print "{},{}".format(list[-1], sum)
or
print "%s,%s" % (list[-1], sum)
If you were using Python3.6+, there would be a third option:
print(f"{list[-1]},{sum}")
Use the sep keyword argument:
print(list[-1], sum, sep=',')
You can use str.format() and pass whatever variables you want to get it formatted, for example:
x = 1
z = [1, 2, 3]
y = 'hello'
print '{},{},{}'.format(x, z[-1], y)
# prints: 1,3,hello

python: convert string into variable name [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
here is my python code:
>>> listName = 'abc'
>>> exec(listName+"=[]")
>>> print listName
>>> 'abc'
excepted output:
>>> print listName
>>> []
I want to define a new variable based on that string.
Even though that may be possible for global (and not local) variables, the better, cleaner, simpler, safer, saner (all in one word: pythonic) way is to use a dictionary for dynamic names:
values = {}
varname = get_dynamic_name()
# set
values[varname] = value
# get
values[varname]

Categories