How to do subtraction in strings - python

How do you print addition in python?
I tried to define addition and tell it to print:
subtraction = int(number - reverse(number))
print str(subtraction)
But it always says:
Traceback (most recent call last):
File "C:\Python25\Castor's Python Programs\proj02.py", line 16, in <module>
subtraction = int(number - reverse(number))
TypeError: unsupported operand type(s) for -: 'str' and 'str'
This is my full code:
import sys
def reverse(num):
return (num)[::-1]
print "This is a puzzle favored by einstein. You will be asked to enter a three digit number, where the hundred's digit differs from the ones digit by at least two. The procedure will always yield 1089."
number = raw_input("Give me a number:")
print "For the number: "
print number
print " the reverse number is: "
print reverse(number)
print "The difference between "
print number
print" and "
print reverse(number)
print " is "
subtraction = int(number - reverse(number))
print str(subtraction)
print "The reverse difference is: "
print str(reverse(subtraction))
print "The sum of: "
print subtraction
print " and revDiff is: "
finaladdition = int(subtraction - reverse(subtraction))
print str(finaladdition)
Can someone please help?

You are trying to subtract two strings, which can't be done. You want to convert those strings to numbers first before you perform the operations:
subtraction = int(number) - int(reverse(number))

You need to convert number to a int before you subtract it. number here is a string confusingly, because it was set by raw_input which returns a string.
subtraction = int(number) - int(reverse(number))
For print str(reverse(subtraction)) to work subtraction must be converted to a string, because it is an int set by subtracting. Thus:
print str(reverse(str(subtraction)))
But reverse will return a string so the str in front is unneeded.
print reverse(str(subtraction))
Also, finaladdition = int(subtraction - reverse(subtraction)) needs to become:
finaladdition = int(subtraction) - int(reverse(str(subtraction)))
We must convert subtraction to a string before passing it to reverse, because reverse uses it's argument as if it is a string. In the first part, subtraction is already a int so converting it to an int is unneeded.

Related

outputting strings and function outputs in Python

I am coding a simple program to add all positive integers not greater than a given integer n. My code:
print("Enter an integer:")
n=input()
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
#print("1+2+3+...+"+str(n)+"="+str(add(n)))
print(add(100))
The function works.
Why does the line in the one line comment not work, if I remove the hash tag? It should - there is a concatenation of four strings. Thank you.
EDIT: the whole output:
Enter an integer:
12
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "<string>", line 6, in add
TypeError: can only concatenate str (not "int") to str
>
input() returns a string. You are passing n=input() which is a string so it is not working as expected.
change it to n=int(input())
Also sum is a reserved keyword and it will be best to change that to a different name
input returns a string, so add(n) will look something like add("1234"). Then, range(k+1) inside the function will be range("1234" + 1), but "1234" + 1 is an error since it's not possible to add a string and a number.
The problem exists in your input, it's current data type is str, and must be converted into int.
Also, it's best if you use .format() when printing strings.
print("Enter an integer:")
n = int(input())
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
print("1 + 2 + 3 + ... + {} = {}".format(n, add(n)))

TypeError: can only concatenate str (not "int") to str123

I am getting an error after running the following code.
Here is the code:
a=input("enter the string value")
b=int(input("enter the number"))
c=a+b
print(c)
Here is result:
enter the string value xyz
enter the number 12
Traceback (most recent call last):
File "e:/python learning/error1.py", line 3, in <module>
c=a+b
TypeError: can only concatenate str (not "int") to str
In Python, you can't add a string to an int. To do so, you can use a different method such as format:
a = input("enter the string value")
b = int(input("enter the number"))
c = "{}{}".format(a, b)
The format function takes objects as parameters and represent them by the str representation of the object.
In Python 3.6 and above, you can use the f-string that will do the same as format by adding an f before the string and the arguments inside like:
c = f'{a}{b}'
Both of the options will store the concatenation of a and b in c.
There is another option using the print function like:
print(a, b, sep="")
The print function takes all arguments separated by a , and prints the str representation of the objects - just like format does. The sep option of printing is by default a space that will print " " in between the arguments. By changing it to "" it will print the arguments sequentially without space in between.
This option can be used without storing the concatenation of a and b in another variable as c.
In python you can't add string value with the different types(int,float,boolean etc).
To get result for this code you have to change one of them either in string type or int type.
a=input()
b=input()
c=a+b
print(c)
Or
a=int(input("enter the number"))
b=int(input("enter the number"))
c=a+b
print(c)
Use this:
a=input("enter the string value")
b=int(input("enter the number"))
c=a+str(b)
print(c)
Output
enter the string valuexyz
enter the number12
xyz12
When you use + with strings, you can only concatenate it with other strings. However you were trying to concatenate it with an integer.
Change c=a+b to c=a+str(b)
str(b) converts b which is an integer to a string.
If your final objectif is to concatenate, you don't realy need to convert your input to int, just use it as input:
a=input("enter the string value")
b=input("enter the number")
c=a+b
print(c)

How to resolve TypeError: can only concatenate str (not "int") to str [duplicate]

This question already has answers here:
How can I concatenate str and int objects?
(1 answer)
How can I read inputs as numbers?
(10 answers)
String concatenate TypeError: can only concatenate str (not "int") to str"
(3 answers)
Closed 2 years ago.
I decided to make some kind of secret code for testing purposes with Unicode.
I've done that by adding numbers to Unicode so it would be kind of secret.
I've been getting this error, but I don't know how to solve it.
Is there any solution?
Original Code
message = input("Enter a message you want to be revealed: ")
secret_string = ""
for char in message:
secret_string += str(chr(char + 7429146))
print("Revealed", secret_string)
q = input("")
Original Error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-182-49ece294a581> in <module>
2 secret_string = ""
3 for char in message:
----> 4 secret_string += str(chr(char + 7429146))
5 print("Revealed", secret_string)
6 q = input("")
TypeError: can only concatenate str (not "int") to str
Updated code
while True:
try:
message = int(input("Enter a message you want to be decrypt: "))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
secret_string += chr(ord(char - str(742146)))
print("Decrypted", secret_string)
q = input("")
Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...
So for example the code below throw an error:
print( "Alireza" + 1980)
like this:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str
To solve the issue, just add str to your number or value like:
print( "Alireza" + str(1980))
And the result as:
Alireza1980
Use f-strings to resolve the TypeError
f-Strings: A New and Improved Way to Format Strings in Python
PEP 498 - Literal String Interpolation
# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'
# same intent with a f-string
i = 15
test = f'Here is a test that can be run {i} times'
print(test)
# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i # will cause a TypeError
# should be
t = f'test{i}'
print(t)
# output
'test15'
The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
Convert the string to an int.
This scenario is specific to this question
When iterating, it's important to be aware of the dtype
i = '15'
# t = 15 + i # will cause a TypeError
# convert the string to int
t = 15 + int(i)
print(t)
# output
30
Note
The preceding part of the answer addresses the TypeError shown in the question title, which is why people seem to be coming to this question.
However, this doesn't resolve the issue in relation to the example provided by the OP, which is addressed below.
Original Code Issues
TypeError is caused because message type is a str.
The code iterates each character and attempts to add char, a str type, to an int
That issue can be resolved by converting char to an int
As the code is presented, secret_string needs to be initialized with 0 instead of "".
The code also results in a ValueError: chr() arg not in range(0x110000) because 7429146 is out of range for chr().
Resolved by using a smaller number
The output is not a string, as was intended, which leads to the Updated Code in the question.
message = input("Enter a message you want to be revealed: ")
secret_string = 0
for char in message:
char = int(char)
value = char + 742146
secret_string += ord(chr(value))
print(f'\nRevealed: {secret_string}')
# Output
Enter a message you want to be revealed: 999
Revealed: 2226465
Updated Code Issues
message is now an int type, so for char in message: causes TypeError: 'int' object is not iterable
message is converted to int to make sure the input is an int.
Set the type with str()
Only convert value to Unicode with chr
Don't use ord
while True:
try:
message = str(int(input("Enter a message you want to be decrypt: ")))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
value = int(char) + 10000
secret_string += chr(value)
print("Decrypted", secret_string)
# output
Enter a message you want to be decrypt: 999
Decrypted ✙✙✙
Enter a message you want to be decrypt: 100
Decrypted ✑✐✐
instead of using " + " operator
print( "Alireza" + 1980)
Use comma " , " operator
print( "Alireza" , 1980)
Use this:
print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
sum += number
print("Total Sum is: %d" %sum )
Problem is you are doing the following
str(chr(char + 7429146))
where char is a string. You cannot add a int with a string. this will cause that error
maybe if you want to get the ascii code and add it with a constant number. if so , you can just do ord(char) and add it to a number. but again, chr can take values between 0 and 1114112
Change secret_string += str(chr(char + 7429146))
To secret_string += chr(ord(char) + 7429146)
ord() converts the character to its Unicode integer equivalent. chr() then converts this integer into its Unicode character equivalent.
Also, 7429146 is too big of a number, it should be less than 1114111

unsupported operand types error in python 3.x when trying to operate on lists

Assuming all ASCII codes are set to variables (a = 97, b = 98, etc).
word = eval(input("What would you like to say? "))
key = 174
print (word)
changedword = (', '.join(str(I + key) for I in word))
print ("Your encrypted string is:" + changedword)
ans1 = input("Would you like to decrypt this?")
print (ans1)
if (ans1 == "yes"):
print (changedword)
decryptedword = (', '.join(str(I - key) for I in changedword))
ans2 = input(decryptedword + " was your decrypted number list. Do you
want to translate to ASCII code?")
if (ans2 == "yes"):
print (', '.join(str(chr(I)) for I in decryptedword))
When running this code I get the error
TypeError: unsupported operand type(s) for -: 'str' and 'int'
in reference to line 11
I am aware that str and int are different, but it worked the first time I used it and I'm not sure how to fix the problem. Any help would be greatly appreciated.
I know that it references encryption a lot, and I know that it's not really an encryption, but I'm new to this and I'm just playing around.
All the extra printing was for my own testing.
Like you said in the question the problem line is:
decryptedword = (', '.join(str(I - key) for I in changedword))
key is an int, but changedword is a str from this line:
changedword = (', '.join(str(I + key) for I in word))
You iterate through changedword for I in changedword and Thus I is also a str type.
So your problem is here I - key when you try to subtract an int from a str.
If you want to use the ascii value to add and subtract use the function ord(c) where c is a single character in a string. When you want to convert it back to a character use the function chr(a) where a is an ascii int

Can't convert 'int' object to str implicitly: Python 3+

My code is supposed to determine and display the number of binary trees after an input.
I keep getting the can't convert int object to str implicitly error and I have no idea how to fix it. It easily works in versions of Python under 3.0, so please help, as I'm still a beginner in Python and I would like to understand what I'm doing wrong.
import sys
print ("Welcome to Binary Tree Enumeration!")
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
def distinct(x):
leafnode = '.'
dp = []
newset = set()
newset.add(leafnode)
dp.append(newset)
for i in range(1,x):
newset = set()
for j in range(i):
for leftchild in dp[j]:
for rightchild in dp[i-j-1]:
newset.add(("(") + leftchild + rightchild + (")"))
dp.append(newset)
return dp[-1]
alltrees = distinct(x+1)
for tree in alltrees:
print (tree)
print ("Thank you for trying this out!")
I forgot to add...this is the error I'm getting.
Traceback (most recent call last):
File "main.py", line 29, in
alltrees = distinct(x+1)
TypeError: Can't convert 'int' object to str implicitly
As others have suggested, this comes from your call to input. In Python27:
>>> input() + 1
3 # I entered that
4
But using raw_input() (which has the same behaviour as input in Python3+):
>>> raw_input() + 1
3 # I entered that
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
And indeed, we have:
>>> x = raw_input()
3
>>> type(x)
<type 'str'>
In your code, your user-input x is a string, and the code complains on the line distinct(x+1) when you try to add a string and an int. Convert it first like this:
>>> x = int(input())
...
In order to concatenate strings and string representations of various types, you have to cast the latter to strings explicitly, e. g.
"(" + str(leftchild) + ", " + str(rightchild) + ")"
or, more readably,
"(%i, %i)" % (leftchild, rightchild)
By default when you use input its always a string input
x = input("Type an integer to output its binary trees: ")
print ("\nYou entered " + str(x))
So there's no need to convert it again !
and here use .format()
newset.add("{0} {1} {2} {3}".format(r"(", leftchild, rightchild, r")"))
But the above one will not maintain the datastructure !!
If you would like to preserve the datastructure, use,
newset.add(tuple(leftchild, rightchild))

Categories