Python - How to concatenate Strings and Integers in Python? - python

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)

Related

Sum operation syntax error

i = 0
while i < 10:
print('print("Hello world '+ str (i*9)+'")')
i = i + 1
I was practicing loop and I wonder why I have to put + after STR(1*9) ??
print('print("Hello world '+ str (i*9)'")') and Why this code has syntax error?
(no plus sign)
I tried put code print(print("Hello world"+str(i*9))) to not use + but I got
Hello world0
None
Hello world9
None
Hello world18
None
To concatenate two string together you need the + operator to tell the python interpreter to specify its some_string plus some_other_string.
Alternatively if you dont like using the + operator you can use .format() like so;
while i < 10:
print("Hello World {0}".format(i*9))
i = i + 1
The string to be inserted goes inside the curly braces. I used 0 inside the curlies because you can add others to your string incrementing the numbers and adding another paramater to the format function.
A + concatenates strings in python. So you need it. Python does not know how to interpret two variables next to each other without , or + or else between them. '")' is also considered a variable in programming context.

exec with ';' in python

I am creating a string, to print the fields in a list, . the fields should be separated by ';', code snippet looks like this( simplified code, not actual )
list = ["abc","xyz","pqr"]
str = "print " + "list[0]" + ";" + "list[2]" # This is dynamically generated
exec (str)
My problem here is, with exec statement, it prints only "xyz" , because of the semi colon. what is the best way to solve this, so that the exec statement prints "xyz;pqr"
You are generating the following code:
print list[0];list[2]
Note that the ; is not quoted. Since a ; is used by Python to separate multiple simple statements on a line, Python executes the print list[0] first, then list[2] (which ends up doing nothing).
You'd have to generate this code instead:
print list[0] + ';' + list[2]
which you could do with:
str = "print " + "list[0]" + " + ';' + " + "list[2]"
However, you should not be using code generation at all. Use standard Python methods to join or format a string. You could use str.format():
print '{};{}'.format(list[0], list[2])
or you could use str.join():
print ';'.join([list[0], list[2]])
If you must vary what code is executed based on some other variables, try to avoid exec still. You could use from __future__ import print_function or encapsulate the print statement in a new function, then call functions dynamically. You can always use a dispatch table to map a string to a function to call, for example.
Try this:
str = "print" + "list[0]" + "';'" + "list[2]"
or
str = "print" + "list[0]" + "/;" + "list[2]"
The problem here is that Python optionally allows semicolons to delimit two separate statements (Compound statements). So when you use exec on the evaluated statement print "abc";"xyz", Python thinks they are two separate statements, hence, only printing "abc".
You could use single quotes around the semicolon to show that it is a string and concatenate them with their surrounding strings:
# Refrain from using list and str as they are built-ins
l = ["abc", "xyz", "pqr"]
s = "print " + "l[0]" + "+';'+" + "l[2]"
exec(s)

How to print brackets in python

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.

How to print spaces in Python?

In C++, \n is used, but what do I use in Python?
I don't want to have to use:
print (" ").
This doesn't seem very elegant.
Any help will be greatly appreciated!
Here's a short answer
x=' '
This will print one white space
print(x)
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello and World
print(f"Hello{x*10}World")
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n) you could just use print without any arguments.
A lone print will output a newline.
print
In 3.x print is a function, therefore:
print()
print("hello" + ' '*50 + "world")
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print or print() will work.
First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:
print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.
To have a line break, and still only one print statement, simply use the "\n" within, as follows:
print("Hello\nWorld.")
Below, I explain spaces, instead of line breaks...
I see allot of people here using the + notation, which personally, I find ugly.
Example of what I find ugly:
x=' ';
print("Hello"+10*x+"world");
The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.
Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.
Let's say you wanted your space to be 8 spaces,
So what I would do would be the following in Python > 3.x
print("Hello", "World.", sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))
The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.
Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:
print("%sHello%sWorld." % (' '*8, ' '*4))
I hope this helps.
P.S. You also could do the following.
>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
Hello World.
rjust() and ljust()
test_string = "HelloWorld"
test_string.rjust(20)
' HelloWorld'
test_string.ljust(20)
'HelloWorld '
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
Sometimes, pprint() in pprint module works wonder, especially for dict variables.
simply assign a variable to () or " ", then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
To print any amount of lines between printed text use:
print("Hello" + '\n' *insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
In Python2 there's this.
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
And to use it, the syntax would be:
Space(4);print("Hello world")
I haven't converted it to Python3 yet.
A lot of users gave you answers, but you haven't marked any as an answer.
You add an empty line with print().
You can force a new line inside your string with '\n' like in print('This is one line\nAnd this is another'), therefore you can print 10 empty lines with print('\n'*10)
You can add 50 spaces inside a sting by replicating a one-space string 50 times, you can do that with multiplication 'Before' + ' '*50 + 'after 50 spaces!'
You can pad strings to the left or right, with spaces or a specific character, for that you can use .ljust() or .rjust() for example, you can have 'Hi' and 'Carmen' on new lines, padded with spaces to the left and justified to the right with 'Hi'.rjust(10) + '\n' + 'Carmen'.rjust(10)
I believe these should answer your question.

Python string operation

I want to get the following output:
"my_www.%first_game_start_time%("REN", "233_736")"
Would you please tell me what is wrong in code below:
u = "my_www.%%first_game_start_time%%(%s, %s)" %("REN", "233_736")
Best Regards
If you are asking how to embed " in the string, triple quotes is an easy way
u = """my_www.%%first_game_start_time%%("%s", "%s")"""%("REN", "233_736")
Another way is to escape the " with a \
u = "my_www.%%first_game_start_time%%(\"%s\", \"%s\")"%("REN", "233_736")
Since you have no ' in the string, you could also use those to delimit the string
u = 'my_www.%%first_game_start_time%%("%s", "%s"))'%("REN", "233_736")
Generally you need to post your expected output and point out the difference between that and the output you receive, or include an error message you are receiving, to get a usable answer. But, I suspect the problem is that you want the value of c to be inserted into the string u and instead the literal letter c is being inserted. If that is the case, the solution is:
c = "222"
u = "my_www.%%first_game_start_time%%(%s, %s, %s)" %("REN", "233_736", c)
I'm going to guess that you want this:
c = "222"
u = "my_www." + first_game_start_time("REN", "233_736", c)

Categories

Resources