- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 Ubuntu 上使用 PyCharm 在 Python 2.7 中编码。
我正在尝试创建一个函数,它将接受一个字符串并将每个字符更改为字母表中的下一个字符。
def LetterChanges(str):
# code goes here
import string
ab_st = list(string.lowercase)
str = list(str)
new_word = []
for letter in range(len(str)):
if letter == "z":
new_word.append("a")
else:
new_word.append(ab_st[str.index(letter) + 1])
new_word = "".join(new_word)
return new_word
# keep this function call here
print LetterChanges(raw_input())
当我运行代码时,出现以下错误:
/usr/bin/python2.7 /home/vito/PycharmProjects/untitled1/test.py
test
Traceback (most recent call last):
File "/home/vito/PycharmProjects/untitled1/test.py", line 17, in <module>
print LetterChanges(raw_input())
File "/home/vito/PycharmProjects/untitled1/test.py", line 11, in LetterChanges
new_word.append(ab_st[str.index(letter) + 1])
ValueError: 0 is not in list
Process finished with exit code 1
我在第 11 行写了什么?如何为每个字符获取字母表中的以下字符并将其附加到新列表?
非常感谢。
最佳答案
我觉得你把事情搞得太复杂了。
只需使用模数滚动到字符串的开头:
from string import ascii_letters
s='abcxyz ABCXYZ'
ns=''
for c in s:
if c in ascii_letters:
ns=ns+ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)]
else:
ns+=c
如果你愿意,你可以将其减少到一个不可读的行:
''.join([ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)]
if c in ascii_letters else c for c in s])
无论哪种情况,
Turns abcxyz ABCXYZ
into bcdyzA BCDYZa
如果你希望它被限制为大小写字母,只需更改导入:
from string import ascii_lowercase as letters
s='abcxyz'
ns=''
for c in s:
if c in letters:
ns=ns+letters[(letters.index(c)+1)%len(letters)]
else:
ns+=c
关于python - 将字符串中的每个字符更改为字母表中的下一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643778/
如何确定字符串是否只包含字母,而我想要的只是 [a-zA-Z]+,那么有什么方法可以通过区域设置确定字母吗? 最佳答案 Character类具有诸如 isLetter 之类的方法它将能够确定一个字符是
有没有更简单的方法将非 html 字母转换为 html 字母?例如,如果我执行 function("a") 它将返回 "a" 我知道如何执行此操作的唯一方法是: def function(text)
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 6 年前。 Improve this ques
这是我希望用字母表添加到我的 UITableView 的改进: 如果我的表中没有不以字母之一开头的结果,我不想在我的 UITableView 中看到这个 titleForHeaderInSection
我有以下代码,可将16位整数的流数据转换为无符号8位整数。 我希望将它们转换为按字母顺序排列的数据值并查看它们包含的内容。 #include int main() { FILE
我目前正在构建一个基于 icu4j 的音译 Web 界面。自动检测用户输入查询的脚本系统的最佳方式是什么? 例如如果输入是 body 里或 عالمتاب 我如何/应该识别它来自哪个脚本系统? 最佳答
字母表(及其索引)可以在这里找到: http://www.garykessler.net/library/base64.html 有没有比 alphabet = ['A','B',...] 更短的方式
为了在 Android 模拟器上显示 Tifinagh 字符,我尝试了这个方法: TextView tv=(TextView)findViewById(R.id.font); Typeface fac
有没有办法使用 Perl '..' 运算符创建 UTF-8 字母数组? 例如,这个是行不通的: $ cat t.pl #!/usr/bin/perl use Data::Dumper; use enc
字母表“a,b,c”上具有相同数量的子串“ab”和“ba”的所有字符串的语言是否是正则的? 我认为答案是否定的,但是很难对其进行正式演示,甚至是非正式演示。 关于如何解决这个问题有什么想法吗? 最佳答
我正在编写一个处理基因序列的程序,我想将每个核苷酸存储在一个字节中,其中每个位代表基因字母表 A,C,G,T 中的一个字母(显然只有一半的比特会被使用)。 我的编码如下: A = 0b1000 C =
所以,我想构建一个正则表达式,我可以传入一个由 0 和 1 组成的字符串(例如“0010101000111100100011110001101100011”),然后确保对于每 6 个连续字符,其中至少
我是一名优秀的程序员,十分优秀!