putting str and int together 4 times not working [duplicate] - python

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 4 years ago.
I have this python program that adds strings to integers:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b
a = int(a)
b = int(b)
c = a + b
str(c)
print "a + b as integers: " + c
I get this error:
TypeError: cannot concatenate 'str' and 'int' objects
How can I add strings to integers?

There are two ways to fix the problem which is caused by the last print statement.
You can assign the result of the str(c) call to c as correctly shown by #jamylak and then concatenate all of the strings, or you can replace the last print simply with this:
print "a + b as integers: ", c # note the comma here
in which case
str(c)
isn't necessary and can be deleted.
Output of sample run:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c

str(c) returns a new string representation of c, and does not mutate c itself.
c = str(c)
is probably what you are looking for

If you want to concatenate int or floats to a string you must use this:
i = 123
a = "foobar"
s = a + str(i)

c = a + b
str(c)
Actually, in this last line you are not changing the type of the variable c. If you do
c_str=str(c)
print "a + b as integers: " + c_str
it should work.

Apart from other answers, one could also use format()
print("a + b as integers: {}".format(c))
For example -
hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))
will result in output - Time elapsed - 13 hours and 32 minutes
Check out docs for more information.

You can convert int into str using string function:
user = "mohan"
line = str(50)
print(user + "typed" + line + "lines")

The easiest and least confusing solution:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c
I found this on http://freecodeszone.blogspot.com/

I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:
def main():
rolling = True; import random
while rolling:
roll = input("ENTER = roll; Q = quit ")
if roll.lower() != 'q':
num = (random.randint(1,6))
print("----------------------"); print("you rolled " + str(num))
else:
rolling = False
main()
I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.

This is what i have done to get rid of this error separating variable with "," helped me.
# Applying BODMAS
arg3 = int((2 + 3) * 45 / - 2)
arg4 = "Value "
print arg4, "is", arg3
Here is the output
Value is -113
(program exited with code: 0)

Related

100 Days of Python - Lesson 37 - Question

I started taking the Dr Angela Yu Python class on Udemy few days ago and I've got a question regarding her "Love Calculator" code :
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
combined_names = name1 + name2
lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
first_digit = t + r + u + e
l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
e = lower_names.count("e")
second_digit = l + o + v + e
score = int(str(first_digit) + str(second_digit))
print(score)
The consol prints out the result below :
Welcome to the Love Calculator!
What is your name?
True Love
What is their name?
True Love
1010
I'd like to understand why the result of print(score) is 1010 and not 88 as there are only 4 characters in each words.
Thank you very much for your help :)
It is because of the letter e which is counted twice for each of the "True Love" inputs because there is an e in true and in love.
So instead of each character being counted once, you have 3 of them counted once and 1 counted twice, which gives 5 count for each word. Since the phrase is repeated, it then becomes 10 counts per word, and the string "10" added to "10" is "1010" and converting that to an integer we get 1010
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n") # True Love
name2 = input("What is their name? \n") # True Love
combined_names = name1 + name2 # True LoveTrue Love
lower_names = combined_names.lower() #true lovetrue love
t = lower_names.count("t") # 2
r = lower_names.count("r") # 2
u = lower_names.count("u") # 2
e = lower_names.count("e") # 4
first_digit = t + r + u + e # 10
l = lower_names.count("l") # 2
o = lower_names.count("o") # 2
v = lower_names.count("v") # 2
e = lower_names.count("e") # 4
second_digit = l + o + v + e # 10
score = int(str(first_digit) + str(second_digit)) # "10" + "10"
print(score) # 1010
I took your code and added in some additional print statements to illustrate why the value comes out as "1010".
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
combined_names = name1 + name2
print("Combined Names:", combined_names)
lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
first_digit = t + r + u + e
print("First Digit:", first_digit)
l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
e = lower_names.count("e")
second_digit = l + o + v + e
print("Second Digit:", second_digit)
score = int(str(first_digit) + str(second_digit))
print(score)
When I run that program and enter in "True Love" for both names, this is the resulting output on the terminal.
#Una:~/Python_Programs/Love$ python3 Love.py
Welcome to the Love Calculator!
What is your name?
True Love
What is their name?
True Love
Combined Names: True LoveTrue Love
First Digit: 10
Second Digit: 10
1010
First off, the entered names are concatenated into a string, "True LoveTrue Love". That string is sampled and the counts are built for the first digit and the second digit. For the first digit, two "t's", two "r's", two "u's" and four "e's" are found in that concatenated string. Therefore the first digit field will contain a value of "10" (2 + 2 + 2 + 4). Likewise, for the second digit calculation, two "l's", two "o's", two "v's", and four "e's" are found in the concatenated string. So again, the sum of those counts is "10". Finally, the two digits are converted to strings and then concatenated. This results in the string value "1010".
So if this calculator program is supposed to derive a different answer, you need to circle back and reevaluate your code.

How to join list elements into strings?

I have a list here where I only need to input 10 letters or strings. I am having a problem separating the list.
print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = ' '.join([str(item) for item in num_string])
print (string)
In my code, for example, I inputted a b c d e f g h i j since it is only 10 inputs. Instead of having an output like a b c d e f g h i j because I used the join method, I want to have a NewLine for every list. So I want it to be like
a
b
c
d
e
f
g
h
i
j
You are almost there just instead of joining a whitespace, join a newline, also you don't need to convert each element to string because each element is a string already because input always returns a string (in Python3) (so this is redundant: str(input()), it is the exact same as: input()):
string = '\n'.join(num_string)
Complete example (removed the redundant str):
print("Please input letter: \n")
num_string = []
num = 10
# the 0 isn't necessary either but
# I guess for clarification it can stay
for i in range(0, num):
element = input(str(i + 1) + ". ")
num_string.append(element)
string = '\n'.join(num_string)
print(string)
Alternatively you can use this (instead of the last two lines in the above code example):
print(*num_string, sep='\n')
And if you really want to shorten the code (it can be as short as 3 lines):
print("Please input letter: \n")
num = 10
print('\n'.join(input(f'{i + 1}. ') for i in range(num)))
print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = '\n' .join([str(item) for item in num_string])
print (string)
Use '\n' , it is like a breakline in your output

Sum of Digits in a specific way in Python

I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()

when i try to decrypt my message in python it says 'string index out of range' in line 8

my code just rearranges the string so that every odd index is moved to the front then the even indexes are moved to the back. now I want to know how do I decrypt this
s = input('please enter a string: ')
for i in range(1,len(s),2):
s = s[ : :2] + s[1: :2]
print('encrypted:',s)
c = input('type your encrypted message to decrypt: ')
for i in range(0,round(len(c)//2,0)+1,2):
c = c[ :i] + c[len(c)//2 +1 + i] + c[i+1: ]
print(c)
Give this a try and see if it's what your looking for.
s = input ('Please enter a string : ')
# incrypt
s = s[::2] + s[1::2]
print (s)
# decrypt
s += ' '
d = ''
half = int (len (s) /2)
for i in range (half) : d += s [i] + s [i + half]
print (d)

concatenation of strings and variables

What I need is for it to print "the sum of 1 and 2 is 3". I'm not sure how to add a and b because I either get an error or it says "the sum of a and b is sum".
def sumDescription (a,b):
sum = a + b
return "the sum of" + a " and" + b + "is" sum
You cannot concat ints to a string, use str.format and just pass in the parameters a,b and use a+b to get the sum:
def sumDescription (a,b):
return "the sum of {} and {} is {}".format(a,b, a+b)
sum is also a builtin function so best to avoid using it as a variable name.
If you were going to concatenate, you would need to cast to str:
def sumDescription (a,b):
sm = a + b
return "the sum of " + str(a) + " and " + str(b) + " is " + str(sm)
Use string interpolation, like this. Python will internally convert the numbers to strings.
def sumDescription(a,b):
s = a + b
d = "the sum of %s and %s is %s" % (a,b,s)
You are trying to concatenate string and int.
You must turn that int to string before hand.
def sumDescription (a,b):
sum = a + b
return "the sum of " + str(a) + " and " + str(b) + " is " + str(sum)

Categories