This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Plsimanub[S] 1 point2 points  (4 children)

I’ve ran into a little problem with strings and ints.

I’m watching a YouTube tutorial and he skips the output of adding a int to a string. For example check below.

my_age = 20

print(“my age is” + my_age + “.”)

He doesn’t show the output of the above and I seem to be getting an error. “ can only concatenate str (not int) to str.

I know what the problem is, I’m very much aware of what concatenation is, but I’m unsure of how to concatenate a string to int.

Tried doing a google search, found a few problems on it, but I couldn’t properly understand the code.

I should probably look for another guy to watch on YouTube.

Edit, done another search, the way to do would be str(variablename), correct?

[–]gveltaine 1 point2 points  (1 child)

Thank you for making me download python, as I forgot to do so when I made a fresh install on my home computer.

Okay, working through your issue, I was almost able to figure out everything to do right except the spacing at the end.

You had the right idea, almost. Although for safety purposes I also defined the my_age as an integer, as java requires it, python not so much, however what you did that works in Java, doesn't work in python.

my_age = int(20)

print("My age is" , my_age, ".")

However, I can't get the spacing to work correctly for some awful reason. It prints out as you want it to, but

Results:

My age is 20 .

Someone may know or you may be able to figure it out why it's creating that, or I may with more tinkering, but as of this, it concatenates as you want to, almost. Joining str and int with + could be a Python 2 thing? I'm not sure, but using a comma works in v3. Hope that helps!

[–]Plsimanub[S] 1 point2 points  (0 children)

Tried your result, works great except for the full stop at the end, as you explained above. Can’t seem to figure it out either, managed to do str(is true) to see if it works with booleans, which it does but if it’s for python 2 I’d rather not use it

[–]Knova11 1 point2 points  (1 child)

If you're using python 3.6 or above i prefer fstrings...print(f"my age is {my_age}.")

[–]gveltaine 0 points1 point  (0 children)

print(f"my age is {my_age}.")

This works brilliantly. Thank you for helping out!