Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
adding a string and an int
#1
I've just started using python and I'm working on a text game. I'm not sure if this is possible but i'm trying to make a variable which is equal to "keys" + 0 while keeping zero an int so i can add to it. I have no idea if its possible but if you know a way of doing this then any help would be appreciated. Here's what I've tried so far:
keys="keys"+0
and
keys=("keys" + 0)
Reply
#2
You cannot add numbers to string, and so you have to do combinations if you want to keep them together.
For instance keeping both in a list, the firts part (index 0) keeping the string, and the second keeping the number.
>>> lst=['keys',0]
>>> lst[0]+str(lst[1])
'keys0'
>>> lst[1]+=1
>>> lst[0]+str(lst[1])
'keys1'

Another solution is to create a class to keep the values. Instantiate the class and you will get a new object with the capabilities you want. It's a bit of work, but a lot of more flexible.
For instance :
class Keys():
	def __init__(self,s,n):
		self.s = s
		self.n = n
	def increment(self):
		self.n += 1
	def __str__(self):
		return self.s + str(self.n)

key = Keys('key',0)
key.increment()
print(key)
gives :
$ python3 tst.py
key1
Reply
#3
Alright. Thank you
Reply
#4
check https://docs.python.org/3.7/library/stri...ing-syntax
conactenation/add is possible between strings, but it's better to use string formatting, e.g.

>>> keys = 'keys {}'.format(0)
>>> keys
'keys 0'
>>> num = 5
>>> keys = f'keys {num}' # f-strings in 3.6+
>>>keys
'keys 5'
in this case you don't need to cast int to str. And also it give you powerful formatting options (see the link above).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding string after every 3rd charater [SOLVED] AlphaInc 2 1,248 Jul-11-2022, 09:22 AM
Last Post: ibreeden
  Adding markers to Folium map only adding last element. tantony 0 2,121 Oct-16-2019, 03:28 PM
Last Post: tantony
  build a list (add_animals) using a while loop, stop adding when an empty string is en nikhilkumar 1 8,885 Jul-17-2017, 03:29 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020