Sum operation syntax error - python

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.

Related

Python str.format with string contatenation and continuation

I'd like to specify a string with both line continuation and catenation characters. this is really useful if I'm echoing a bunch of related values. Here is a simple example with only two parameters:
temp = "here is\n"\
+"\t{}\n"\
+"\t{}".format("foo","bar")
print(temp)
here's what I get:
here is
{}
foo
And here is what I expect:
here is
foo
bar
What gives?
You can try something like this :
temp = ("here is\n"
"\t{}\n"
"\t{}".format("foo","bar"))
print(temp)
Or like :
# the \t have been replaced with
# 4 spaces just as an example
temp = '''here is
{}
{}'''.format
print(temp('foo', 'bar'))
vs. what you have:
a = "here is\n"
b = "\t{}\n"
c = "\t{}".format("foo","bar")
print( a + b + c)
str.format is called before your strings are concatenated. Think of it like 1 + 2 * 3, where the multiplication is evaluated before the addition.
Just wrap the whole string in parentheses to indicate that you want the strings concatenated before calling str.format:
temp = ("here is\n"
+ "\t{}\n"
+ "\t{}").format("foo","bar")
Python in effect sees this:
Concatenate the result of
"here is\n"
with the resuslt of
"\t{}\n"
with the result of
"\t{}".format("foo","bar")
You have 3 separate string literals, and only the last one has the str.format() method applied.
Note that the Python interpreter is concatenating the strings at runtime.
You should instead use implicit string literal concatenation. Whenever you place two string literals side by side in an expression with no other operators in between, you get a single string:
"This is a single" " long string, even though there are separate literals"
This is stored with the bytecode as a single constant:
>>> compile('"This is a single" " long string, even though there are separate literals"', '', 'single').co_consts
('This is a single long string, even though there are separate literals', None)
>>> compile('"This is two separate" + " strings added together later"', '', 'single').co_consts
('This is two separate', ' strings added together later', None)
From the String literal concatenation documentation:
Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".
When you use implicit string literal concatenation, any .format() call at the end is applied to that whole, single string.
Next, you don't want to use \ backslash line continuation. Use parentheses instead, it is cleaner:
temp = (
"here is\n"
"\t{}\n"
"\t{}".format("foo","bar"))
This is called implicit line joining.
You might also want to learn about multiline string literals, where you use three quotes at the start and end. Newlines are allowed in such strings and remain part of the value:
temp = """\
here is
\t{}
\t{}""".format("foo","bar")
I used a \ backslash after the opening """ to escape the first newline.
The format function is only being applied to the last string.
temp = "here is\n"\
+"\t{}\n"\
+"\t{}".format("foo","bar")
Is doing this:
temp = "here is\n" + "\t{}\n"\ + "\t{}".format("foo","bar")
The key is that the .format() function is only happening to the last string:
"\t{}".format("foo","bar")
You can obtain the desired result using parentheses:
temp = ("here is\n"\
+"\t{}\n"\
+"\t{}").format("foo","bar")
print(temp)
#here is
# foo
# bar

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)

Python - How to concatenate Strings and Integers in 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)

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 Concatenation - concatenating '\n'

I am new to Python and need help trying to understand two problems i am getting relating to concatenating strings. I am aware that strings can be added to concatenate each other using + symbol like so.
>>> 'a' + 'b'
'ab'
However, i just recently found out you do not even need to use the + symbol to concatenate strings (by accident/fiddling around), which leads to my first problem to understand - How/why is this possible!?
>>> print 'a' + 'b'
ab
Furthermore, I also understand that the '\n' string produces a 'newline'. But when used in conjunction with my first problem. I get the following.
>>> print '\n' 'a'*7
a
a
a
a
a
a
a
So my second problem arises - "Why do i get 7 new lines of the letter 'a'. In other words, shouldn't the repeater symbol, *, repeat the letter 'a' 7 times!? As follows.
>>> print 'a'*7
aaaaaaa
Please help me clarify what is going on.
When "a" "b" is turned into "ab", this ins't the same as concatenating the strings with +. When the Python source code is being read, adjacent strings are automatically joined for convenience.
This isn't a normal operation, which is why it isn't following the order of operations you expect for + and *.
print '\n' 'a'*7
is actually interpreted the same as
print '\na'*7
and not as
print '\n' + 'a'*7
Python concatenates strings together when you do not separate them with a comma:
>>> print 'a' 'b'
ab
>>> print 'a', 'b'
a b
So you are actually printing '\na' 7 times.
I'm not sure what you mean by "how is it possible". You write a rule: two strings next to each other get concatenated. Then you implement it in the parser. Why? Because it allows you do conveniently do things like this:
re.findall('(<?=(foo))' # The first part of a complicated regexp
'>asdas s' # The next part
'[^asd]' # The last part
)
That way, you can describe just what you're doing.
When you do A * B + C, the computer always does A times B first, then adds C, because multiplication comes before addition.
When you do string concatenation by putting the string literals next to each other, and multiplication, the special string concatenation comes first. This means '\n' 'a' * 7 is the same as ('\n' 'a') * 7, so the string you're repeating is '\na'.
You've probably already realised that relying on the implicit concatenation of adjacent strings is sometimes problematic. Also, concatenating with the + operator is not efficient. It's not noticeable if joining only a few small strings, but it is very noticeable at scale.
Be explicit about it; use ''.join()
print '\n'.join(['a'*7])

Categories

Resources