英文:
Incrementing Strings in Python
问题
如何在Python中增加字符串?例如,x应该变为y,y变为z,z变为a。
请注意,只有最后一个字母应该更改。例如,单词Ved应该更改为Vee,而不是Wfe
其他示例:xyz应该增加到xza。
def increment(password):
char = password[-1]
i = ord(char[0])
i += 1
if char == 'z':
return password[:-1] + 'a'
char = chr(i)
return password[:-1] + char
英文:
How do I increment strings in python? For example, x should change to y, y to z, z to a.
Please note that only the last letter should change. For example, the word Ved should change to Vee, and not Wfe
Other examples: xyz should increment to xza.
def increment(password):
char = password[-1]
i = ord(char[0])
i += 1
if char == 'z':
return password[:-2] + increment(password[-2]) + 'a'
char = chr(i)
return password[:-1] + char
答案1
得分: 0
这基本上是一个凯撒密码,可以使用str.translate
方法实现:
from string import ascii_lowercase as letters
# 构建小写字母的映射,偏移1位
m = str.maketrans(dict(zip(letters, (letters[1:] + 'a'))))
# 拆分字符串
s = 'xyz'
first, last = s[0], s[1:]
# 使用预先构建的映射进行翻译
newlast = last.translate(m)
print(''.join((first, newlast)))
'xza'
英文:
This is basically a cesar cipher, and can be implemented using the str.translate
method:
from string import ascii_lowercase as letters
# build your map of all lowercase letters
# to be offset by 1
m = str.maketrans(dict(zip(letters, (letters[1:] + 'a'))))
# split your string
s = 'xyz'
first, last = s[0], s[1:]
# make the translation using your prebuilt map
newlast = last.translate(m)
print(''.join((first, newlast)))
'xza'
</details>
# 答案2
**得分**: 0
我们可以使用与'z'的直接比较,因为问题暗示密码必须以小写字母结尾。所以代码如下:
```python
def increment(password):
if password:
if (c := password[-1]) == 'z':
return password[:-1] + 'a'
return password[:-1] + chr(ord(c)+1)
return password
英文:
We can use a direct comparison with 'z' as the question implies that the password must end with a lowercase letter. So it's just:
def increment(password):
if password:
if (c := password[-1]) == 'z':
return password[:-1] + 'a'
return password[:-1] + chr(ord(c)+1)
return password
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论