i want to print "(" in python
print "(" + var + ")"
but it says:
TypeError: coercing to Unicode: need string or buffer, NoneType found
can somebody help me? that cant be too hard... -.-
Using string formatting:
foo = 'Hello'
print('({})'.format(foo))
maybe a simple print "(" + str(var) + ")"?
it appears that var is None in what you provided. Everything is correct, but var does not contain a string.
Try this:
var = 'Hello World!'
print('(' + var + ')')
Also, your code works well on Python 2.7.4, so long as you pre-define var.
Related
repalce a string with python
I have tried the replace function but it gives me an str error
a="test1,test2"
a="\""+a.replace(",","\",\"")+"\""
print(a)
So this is the answer to what you asked.
old_string = "test1,test2"
new_string = old_string.replace(',', '","')
# new_string = 'test1","test2'
When you want to use " in a string, you can use the single quote for the string.
However are you sure you are not looking for the split functionality.
I would like to evaluate a string that contains double quotes, for example as a function parameter or in an assignment:
argument = "string with \"quotes\"" # any value, e.g., read from file.
value = eval("\"" + argument + "\"")
fails:
string with "quotes"
^
SyntaxError: invalid syntax
I know I could use value = eval("\'" + argument + "\'") instead, but now this is going to fail when argument = "string with 'quotes'".
And I would like something robust that works with any string argument (e.g., read in a file) with the objective to actually use it as a function (string) parameter, maybe like that: eval("f(" + "\"" + argument + "\"" + ")").
I don't think this is your intended result, but maybe something like this?
backslash="\\"
argument = "some " + backslash + "\"data" + backslash + "\" quoted data"
value = eval("\"" + argument + "\"")
print(value)
Per the subject, I'm trying to print each sentence in a string on a new line. With the current code and output shown below, what's the syntax to return "Correct Output" shown below?
Code
sentence = 'I am sorry Dave. I cannot let you do that.'
def format_sentence(sentence):
sentenceSplit = sentence.split(".")
for s in sentenceSplit:
print s + "."
Output
I am sorry Dave.
I cannot let you do that.
.
None
Correct Output
I am sorry Dave.
I cannot let you do that.
You can do this :
def format_sentence(sentence) :
sentenceSplit = filter(None, sentence.split("."))
for s in sentenceSplit :
print s.strip() + "."
There are some issues with your implementation. First, as Jarvis points out in his answer, if your delimiter is the first or last character in your string or if two delimiter characters are right next to each other, None will be inserted into your array. To fix this, you need to filter out the None values. Also, instead of using the + operator, use formatting instead.
def format_sentence(sentences):
sentences_split = filter(None, sentences.split('.'))
for s in sentences_split:
print '{0}.'.format(s.strip())
You can split the string by ". " instead of ".", then print each line with an additional "." until the last one, which will have a "." already.
def format_sentence(sentence):
sentenceSplit = sentence.split(". ")
for s in sentenceSplit[:-1]:
print s + "."
print sentenceSplit[-1]
Try:
def format_sentence(sentence):
print(sentence.replace('. ', '.\n'))
I have the following problem: This returns "\n" in the output, but I want it to return a newline like an SQL query, can anyone help me with this?
IDLE, Python 2.7.5.
int iD, str days, int maxCapacity, int crn, int enrollment, string semester, string room
python code:
def registerCourse(iD, days, maxCapacity, crn, enrollment, semester, room):
return "UPDATE CoursesOffered" + "\n" + "SET InstructorID=" + str(iD) + ",Days=" + str(days) + ",MaxCapacity=" + str(maxCapacity) + ",Enrollment=" + str(enrollment) + "\n" + "WHERE CRN=" + str(crn)
I guess the real question is: How do I get this in the string format and return it? I am trying to get this to be a directly executed SQL query.
"\n" is just a representation of a newline.
>>> a = 'a\nb'
>>> a
'a\nb'
>>> print (a)
a
b
Try passing the value to the print function (or statement in py2, but the parentheses never hurt).
NOTA BENE
If possible, restrain from using string-functions to pass parameters to a query. This opens all doors for SQL-injection and weakens the veil between our world and the nether realms, arosing HIM who waits behind the wall. Pass your parameters through the driver.
For example, what happens if crn equals '1 or true', or if it equals '1;drop table CoursesOffered'.
That function returns a string. If you print the string, it will render with a new line. For example:
>>> def foo():
... return "Hi \n This is on a new line."
...
>>> foo()
'Hi \n This is on a new line.'
>>> print foo()
Hi
This is on a new line.
I'm with some trouble getting this code to work:
count_bicycleadcategory = 0
for item_bicycleadcategory in some_list_with_integers:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory
count_bicycleadcategory = count_bicycleadcategory + 1
I'm getting an error:
Type Error, not all arguments converted during string formatting
My question is: Any clue on how I pass the "item_bicycleadcategory" to the exec expression?
Best Regards,
You are already using python's format syntax:
"string: %s\ndecimal: %d\nfloat: %f" % ("hello", 123, 23.45)
More info here: http://docs.python.org/2/library/string.html#format-string-syntax
First, exec is even more dangerous than eval(), so be absolutely sure that your input is coming from a trusted source. Even then, you shouldn't do it. It looks like you're using a web framework or something of the sort, so really don't do it!
The problem is this:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory
Take a closer look. You're trying to put the string formatting argument to a single parentesis with no format strings with ')' % count_bicycleadcategory.
You could do this:
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' % count_bicycleadcategory + str(item_bicycleadcategory) + ')'
But what you really should be doing is not using exec at all!
Create a list of your model instances and use that instead.
for python 2.7 you could use format:
string = '{0} give me {1} beer'
string.format('Please', 3)
out:
Please give me 3 beer
you could do many things with format, for example:
string = '{0} give me {1} {0} beer'
out:
Please give me 3 Please beer.
try this :
exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%s)' % (count_bicycleadcategory, str(item_bicycleadcategory))
(you mustn't mix %s and string + concatenation at the same time)
Try this:
exec 'model_bicycleadcategory_%d.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%d)' % (count_bicycleadcategory, item_bicycleadcategory)