在Python中递增字符串

huangapple go评论67阅读模式
英文:

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]) == &#39;z&#39;:
            return password[:-1] + &#39;a&#39;
        return password[:-1] + chr(ord(c)+1)
    return password

huangapple
  • 本文由 发表于 2023年6月15日 00:07:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定