Reputation: 392
Suppose you have a string s
and an integer array roll
. I want to increment each of the letters of s
by 1 depending on the number in roll
. For example, if s = "abc"
and roll = [1,2]
, then the output would be s = "ccc"
.
When I run the below code, I keep getting the original string s
Why is this?
def rollTheString(s, roll):
for i in range(0, len(roll)):
for j in range(0,i):
s[j] = (chr(ord(s[j])+1));
return s;
Upvotes: 1
Views: 6923
Reputation: 61
you can use this
def rollTheString(s, roll):
increment = [0] * len(s)
a_to_z = [chr(i) for i in range(97, 97 + 26)]
for num in roll:
for i in range(num):
increment[i] += 1
result = ""
for i in range(len(s)):
index = ord(s[i]) + increment[i] - 97
index = index % 26
result += a_to_z[index]
return result
Upvotes: 2
Reputation: 378
The error you get, should be:
TypeError: 'str' object does not support item assignment
This is due to the fact that in Python strings are immutable, so you can't change their characters in-place.
As to your problem, consider the following code:
def rollTheString(s, roll):
i = 0
tmp = ''
while i < len(s):
ch_offset = roll[i] if ( i < len(roll)) else 0
tmp += (chr(ord(s[i]) + ch_offset))
i += 1
return tmp
newString = rollTheString("abc", [2,1])
print (newString)
Upvotes: 1
Reputation: 109546
Strings are immutable, so you cannot change them via slicing. You'll need to create a new string, preferably through a comprehension using join
.
from itertools import izip_longest
s = "abc"
roll = [1, 2]
>>> "".join(chr(ord(c) + (n or 0)) for c, n in izip_longest(s, roll))
'bdc'
# a + 1 = b, b + 2 = d, c + 0 = c
Looking at your nest loops, you may be creating a cumsum of sorts on the roll. You don't even appear to use the values in roll
, just its length.
I would split your problem into two parts:
s
.join
method illustrated above to create a new string based on the offsets.Upvotes: 1