I have a string like
strTemp='i don\'t want %s repeat the %s variable again %s and again %s'%('aa','aa','aa','aa')
I want to replace all the %s with 'aa', so I have to repeat the 'aa' for many times, how can I tell the program that I want to replace all the %s just with the same variable, so I needn't type the variable for times
The % operator is discouraged. Use str.format instead.
strTemp='i don\'t want {0} repeat the {0} variable again {0} and again {0}'.format('aa')
You could use the named formatting argument syntax:
strTemp='i don\'t want %(key)s repeat the %(key)s variable again %(key)s and again %(key)s' % {
'key': 'replacement value',
}
Not a lot better necessarily since you have to repeat a key four times, but if your replacement value is long, or is a calculation with side effects that you really don't want to do more than once, this is a good option.
if you have really many repetitions and don't want to type {0} or %(var)s you may consider a seldom used (placeholder-)char, which gets replaced, e.g.:
p='µ µµ µµµ µµµµ µµµµµ {1}'.replace('µ','{0}').format(' muahaha ', 'duh')
or for a single substition variable:
strTemp='i don\'t want µ repeat the µ variable again µ and again µ'.replace('µ','aa')
Related
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
If I have a string for example:
value = ("The value is at $500.00 today, check again please.")
And I have a table (df or list or something) of values, would it be possible to replace the "$500.00" at a set interval or whenever the script runs?
For example, if tomorrows value was $650.00 and so on, then without changing the string manually, could I keep replacing that segment of the string?
Cheers
There is multiple ways to solve your problem!
If you search for "Python string formatting" you will find a lot of examples etc.
value = "$500"
# one way
message = "The value is at %s today, check again please."
print(message % value)
# another way
message2 = "The value is at {0} today, check again please."
print(message2.format(value))
If your value is actually an int you can deal with it by converting your int to a str first.
value = 500
message = "The value is at $%s today, check again please."
print(message % str(value))
Python 3's f-Strings offer an even better syntax for this:
value = 500.00
message = f'The value is at ${value} today, check again please.'
print(message)
# output: The value is at $500.0 today, check again please.
Read more about Python3 fstrings here.
you could use str.format:
my_list = ['$500.00', '$600.00']
value = "The value is at {} today, check again please."
print(value.format(my_list[0]))
print(value.format(my_list[1]))
output:
The value is at $500.00 today, check again please.
The value is at $600.00 today, check again please.
What is the difference between defining a variable and using it in a string and putting %s in a string and passing in the value after?
site = "Stackoverflow"
site + " is great!"
"%s is great!" % "Stackoverflow"
Printing either of these gives the same result so when is it better to use one over the other?
If you want to keep certain string constants in the same file, or on the top most of the file, you can declare the string with the placeholders as constants, then replace the placeholders with actual variable at run time through the % syntax.
This also allows greater re-usability.
Eg. you can store a single constant "%s is %s years old".
Using this syntax might also make the string more readable.
For two strings, there is little difference.
For multiple strings, s1 + s2 + s3 is less efficient, as it has to create a temporary str object for the first concatenation, where as both "%s %s %s" % (s1, s2, s3) and "{} {} {}".format(s1, s2, s3) creates the final str object immediately.
One:
'string' + 'string'
Two:
'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')
There is a great article on this here: https://pyformat.info/
Also the docs are a great resource: https://docs.python.org/2/library/string.html#format-string-syntax
Version one is less efficient with larger amounts of concatenation.
How do I replace %s with a defined/non-empty variable string? Or rather what is the Pythonic or syntactic sugar for doing so?
Example:
# Replace %s with the value if defined by either vehicle.get('car') or vehicle.get('truck')
# Assumes only one of these values can be empty at any given time
# The get function operates like http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get
logging.error("Found duplicate entry with %s", vehicle.get('car') or vehicle.get('truck'))
I think you want this:
'Found duplicate entry with %s' % (vehicle.get('car') or vehicle.get('truck'))
This will replace the '%s' with the non-empty string (assuming only one is non-empty). If both contain text, it will be replaced with the output of vehicle.get('car')
You could also use this type of string formatting:
'Found duplicate entry with {0}'.format(vehicle.get('car') or vehicle.get('truck'))
This will return the same result.
Have you tried something like this?
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck')))
Or if truck is also empty, you can return a default value:
logging.error("Found duplicate entry with %s" % (vehicle.get('car') or vehicle.get('truck', 'default')))
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Unpythonic way of printing variables in Python?
In PHP one can write:
$fruit = 'Pear';
print("Hey, $fruit!");
But in Python it's:
fruit = 'Pear'
print("Hey, {0}!".format(fruit))
Is there a way for me to interpolate variables in strings instead? And if not, how is this more pythonic?
Bonus points for anyone who gets the reference
The closest you can get to the PHP behaviour is and still maintaining your Python-zen is:
print "Hey", fruit, "!"
print will insert spaces at every comma.
The more common Python idiom is:
print "Hey %s!" % fruit
If you have tons of arguments and want to name them, you can use a dict:
print "Hey %(crowd)s! Would you like some %(fruit)s?" % { 'crowd': 'World', 'fruit': 'Pear' }
The way you're doing it now is a pythonic way to do it. You can also use the locals dictionary. Like so:
>>> fruit = 'Pear'
>>> print("Hey, {fruit}".format(**locals()))
Hey, Pear
Now that doesn't look very pythonic, but it's the only way to achieve the same affect you have in your PHP formatting. I'd just stick to the way you're doing it.
A slight adaptation from the NamespaceFormatter example in PEP-3101:
import string
class NamespaceFormatter(string.Formatter):
def __init__(self, namespace={}):
super(NamespaceFormatter, self).__init__()
self.namespace = namespace
def get_value(self, key, args, kwds):
if isinstance(key, str):
try:
# Check explicitly passed arguments first
return kwds[key]
except KeyError:
return self.namespace[key]
else:
super(NamespaceFormatter, self).get_value(key, args, kwds)
fmt = NamespaceFormatter(globals())
fruit = 'Pear'
print fmt.format('Hey, {fruit}!')
for:
Hey, Pear!
Something like this should work:
"%(fruit)s" % locals()
Don't do it. It is unpythonic. As example, when you add translations to your app, you can't longer control which variables are used unless you check all the translations files yourself.
As example, if you change a local variable, you'll have to change it in all translated strings too.