print("*" * 10) this line in python print * 10 times.
However the when trying to print("*" + 10) there is a type error.
Why is there a difference in operator behaviour with str and int
print("*" * 10) this line in python print * 10 times.
However the when trying to print("*" + 10) there is a type error.
Why is there a difference in operator behaviour with str and int
That's because + is a concatenator in Python, and you can concatenate two strings but not a string and an int. You can, of course, cast the int into a string and concatenate that with another string if that's what you want to do: print("*" + (str(10)))
The thing works with * because that operator will simply concatenate the string with itself as many times as indicated by the integer number, as you've observed.
I hope you are well,
The asterisk (star)(*) operator is used in Python with more than one meaning attached to it.
a=10
b=20
a*b
returns 200, but For sequences such as string, list and tuple, * is a repetition operator
m="Hello World."
m*3
it returns , 'Hello World.Hello World.Hello World'
Single asterisk as used in function declaration allows variable number of arguments passed from calling environment. Inside the function it behaves as a tuple.
def function(*arg):
for i in arg:
print (i)
It returns all the items in the args.
You can import all the functions of a library or python script with using single star(*)
from math import *
but for the "+" if you want to use between 2 variables with (int) and (str), it will give and error, because "+" can sum same types together.
I hope it answers your doubt.
Well, there is a difference because it is a different operator, and operations of addition between str and int have not been implemented in Python.
Mostly because it is ambiguous. What would print("*" + 10) mean? Would it mean to concatenate the int as if it were a string as "*10", or to add 10 to each character's ASCII value, or to evaluate the string as an int and then apply normal addition? Because of this ambiguity, it has been left unimplemented.