This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 8 years ago.
I have a string that contains a % that I ALSO want to use %s to replace a section of that string with a variable. Something like
name = 'john'
string = 'hello %s! You owe 10%.' % (name)
But when I run it, I get
not enough arguments for format string
I'm pretty sure that means that python thinks I'm trying to insert more than 1 variable into the string but only included the one. How do I overcome this? Thanks!
You can use a % in your string using this syntax, by escaping it with another %:
>>> name = 'John'
>>> string = 'hello %s! You owe 10%%.' % (name)
>>> string
'hello John! You owe 10%.'
More about: String Formatting Operations - Python 2.x documentation
As #Burhan added after my post, you can bypass this problem by using the format syntax recommended by Python 3:
>>> name = 'John'
>>> string = 'hello {}! You owe 10%'.format(name)
>>> string
'Hello John! You owe 10%'
# Another way, with naming for more readibility
>>> string = 'hello {name}! You owe 10%.'.format(name=name)
>>> str
'hello John! You owe 10%.'
In addition to what Maxime posted, you can also do this:
>> name = 'john'
>>> str = 'Hello {}! You owe 10%'.format(name)
>>> str
'Hello john! You owe 10%'
Related
This question already has answers here:
Why is my print function printing the () and the "" along with the statement?
(2 answers)
Closed 5 years ago.
I am learning Python and I run into a syntax problem. When I try to create a function that prints "Hello (name)", the quotation marks and the comma appear alongside the string.
For example:
def sayHello(name = 'John'):
print('Hello ', name)
sayHello()
prints as:
('Hello ', 'John')
Any idea why it's the case?
Thanks!
You code would work as expected in Python 3.
Python 2 uses print statement, i.e command, rather than function.
The command understands your argument as a tuple (pair).
Correct use of print command in Python 2
print 'Hello,' name
Alternatives are
print 'Hello, %s' % name
See Using print() in Python2.x
for details
In python, () means a tuple. It will print "()" if its empty, and "(value1, value2, ...)" if it contains values.
In your example, you print a tuple which contains two values "Hello" and name.
If you want to print "Hello (name)", you could try:
print "Hello ", name
print "Hello " + name
My code looks like this:
name = Joe
print "Hello", name, "!"
My output looks like:
Hello Joe !
How do I remove the space between Joe and !?
There are several ways of constructing strings in python. My favorite used to be the format function:
print "Hello {}!".format(name)
You can also concatenate strings using the + operator.
print "Hello " + name + "!"
More information about the format function (and strings in general) can be found here:
https://docs.python.org/2/library/string.html#string.Formatter.format
6 Years Later...
You can now use something called f-Strings if you're using python 3.6 or newer. Just prefix the string with the letter f then insert variable names inside some brackets.
print(f"Hello {name}")
a comma after print will add a blank space.
What you need to do is concatenate the string you want to print; this can be done like this:
name = 'Joe'
print 'Hello ' + name + '!'
Joe must be put between quotes to define it as a string.
>>> print (name)
Joe
>>> print('Hello ', name, '!')
Hello Joe !
>>> print('Hello ', name, '!', sep='')
Hello Joe!
You can also use printf style formatting:
>>> name = 'Joe'
>>> print 'Hello %s !' % name
Hello Joe !
One other solution would be to use the following:
Print 'Hello {} !'.format(name.trim())
This removes all the leading and trailing spaces and special character.
Does Python have a function to neatly build a string that looks like this:
Bob 100 Employee Hourly
Without building a string like this:
EmployeeName + ' ' + EmployeeNumber + ' ' + UserType + ' ' + SalaryType
The function I'm looking for might be called a StringBuilder, and look something like this:
stringbuilder(%s,%s,%s,%s, EmployeeName, EmployeeNumber, UserType, SalaryType, \n)
Normally you would be looking for str.join. It takes an argument of an iterable containing what you want to chain together and applies it to a separator:
>>> ' '.join((EmployeeName, str(EmployeeNumber), UserType, SalaryType))
'Bob 100 Employee Hourly'
However, seeing as you know exactly what parts the string will be composed of, and not all of the parts are native strings, you are probably better of using format:
>>> '{0} {1} {2} {3}'.format(EmployeeName, str(EmployeeNumber), UserType, SalaryType)
'Bob 100 Employee Hourly'
Your question is about Python 2.7, but it is worth note that from Python 3.6 onward we can use f-strings:
place = 'world'
f'hallo {place}'
'hallo world'
This f prefix, called a formatted string literal or f-string, is described in the documentation on lexical analysis
You have two options here:
Use the string .join() method: " ".join(["This", "is", "a", "test"])
Use the percent operator to replace parts of a string: "%s, %s!" % ("Hello", "world")
As EmployeeNumber is a int object , or may you have may int amount your variables you can use str function to convert them to string for refuse of TypeError !
>>> ' '.join(map(str,[EmployeeName, EmployeeNumber,UserType , SalaryType]))
'Bob 100 Employee Hourly'
Python has two simple ways of constructing strings:
string formatting as explained here: https://docs.python.org/2/library/string.html
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
and the old style % operator
https://docs.python.org/2.7/library/stdtypes.html#string-formatting
>>> print '%(language)s has %(number)03d quote types.' % \
... {"language": "Python", "number": 2}
Python has 002 quote types.
This question already has answers here:
Is there a Python equivalent to Ruby's string interpolation?
(9 answers)
Closed 8 years ago.
In Ruby I can do this:
"This is a string with the value of #{variable} shown."
How do I do that same thing in Python?
You have a lot of options.
"This is a string with the value of " + str(variable) + " shown."
"This is a string with the value of %s shown." % (str(variable))
"This is a string with the value of {0} shown.".format(variable)
The modern/preferred way is to use str.format:
"This is a string with the value of {} shown.".format(variable)
Below is a demonstration:
>>> 'abc{}'.format(123)
'abc123'
>>>
Note that in Python versions before 2.7, you need to explicitly number the format fields:
"This is a string with the value of {0} shown.".format(variable)
this is one of the way we can also do
from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')
I'm new to Python and after this one script I probably won't work with Python at all. I'm extracting some data using Scrapy and have to filter out some string (I've already done this with digits using isdigit()). Googling gives me pages about filtering out special strings, but what I want is really just a small part of a larger string.
This is the string:
Nima Python: how are you?
What I want left:
how are you?
so this part removed:
Nima Python:
Thanks in advance guys.
This works:
>>> s = "Nima Python: how are you?"
>>> s.replace("Nima Python: ", "") # replace with empty string to remove
'how are you?'
I'm assuming there will be other strings like this... so I'm guessing str.split() might be a good bet.
>>> string = "Nima Python: how are you (ie: what's wrong)?"
>>> string.split(': ')
['Nima Python', 'how are you (ie', " what's wrong)?"]
>>> string.split(': ', 1)[1]
"how are you (ie: what's wrong)?"
>>> string = 'Nima Python: how are you?'
>>> string.split(':')[1].strip()
'how are you?'
String slicing: (This is the easiest way, but isn't very flexible)
>>> string = "Nima Python: how are you?"
>>> string
'Nima Python: how are you?'
>>> string[13:] # Used 13 because we want the string from the 13th character
'how are you?'
String replace:
>>> string = "Nima Python: how are you?"
>>> string.replace("Nima Python: ", "")
'how are you?'
String split: (splitting the string into two parts using the ":")
>>> string = "Nima Python: how are you?"
>>> string.split(":")[1].strip()
'how are you?'