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)
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
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).