-2

I am trying to increment the following string in the variable, tmp='5a' to '5b'. I found online a solution that allows me to increment a character using chr(ord('a') + 1) to get b.

But, I am not able to understand how can I perform the same operation on the variable tmp.

May someone help me.

Analia
  • 83
  • 1
  • 11
  • Does this answer your question? [Python - Increment Characters in a String by 1](https://stackoverflow.com/questions/35820678/python-increment-characters-in-a-string-by-1) – Tomerikoo Dec 15 '20 at 20:30
  • Can you be more specific? What have you tried, with what are you struggling? What are the assumptions on your string? What's the possible length, letters, will the letters always be in the same location? Please be more clear – Tomerikoo Dec 15 '20 at 20:37

2 Answers2

2

If you are looking for increments of a hexadecimal string, you can do it like this:

tmp = "5a"
tmp = f"{int(tmp,16)+1:x}"

print(tmp) # '5b'

on the other hand if you only want to increment the last letter, you can do this:

tmp = tmp[:-1]+chr(ord(tmp[-1])+1)

To increase all letters in the strings, you can use the translate method:

letters = 'abcdefghijklmnopqrstuvwxyz'
upOne   = str.maketrans(letters[:-1],letters[1:])
result  = "abcde".translate(upOne)  # 'bcdef'
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • What if I want to do increment to a string like 'abcde' and get a return 'bcdef'? – Guacaka283 Sep 19 '21 at 19:22
  • @Guacamole6, That would be applying the 2nd solution to every character in the string, but there is something easier using the translate method (see my last addition to the answer) – Alain T. Sep 19 '21 at 19:44
  • Thanks for your response. I actually got a more complicated question than this one here. I tried to do increment to a string 'hello world!' and hope to get 'ifmmp xpsme!'. Seems like the translate method doesn't apply to my question. Do you have a better idea of how to deal with my question? – Guacaka283 Sep 19 '21 at 20:36
  • Please add a new question, I wouldn't want to further bastardize this answer. BTW I do get `'ifmmp xpsme!'` when I do `"hello world!".translate(upOne)` – Alain T. Sep 19 '21 at 20:38
-1

Try this:

def increment(val):
    return val[:-1]+chr(ord(val[-1])+1)

tmp="5a"
increment(tmp)
print(tmp)

You can do that to increment the last character of a string.

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34