首页 / PYTHON / Python中的文本转换功能
Python中的文本转换功能
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python中的文本转换功能,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1395字,纯文字阅读大概需要2分钟。
内容图文
![Python中的文本转换功能](/upload/InfoBanner/zyjiaocheng/707/6fd86f05bdcc4e3abc2bb0a5b2b085a7.jpg)
我正在编写代码,因此你可以在字母表中的两个位置移动文本:’ab cd’应该变为’cd ef’.我正在使用Python 2,这是我到目前为止所得到的:
def shifttext(shift):
input=raw_input('Input text here: ')
data = list(input)
for i in data:
data[i] = chr((ord(i) + shift) % 26)
output = ''.join(data)
return output
shifttext(3)
我收到以下错误:
File "level1.py", line 9, in <module>
shifttext(3)
File "level1.py", line 5, in shifttext
data[i] = chr((ord(i) + shift) % 26)
TypError: list indices must be integers, not str
所以我必须以某种方式将字母改为数字?但我以为我已经这样做了?
解决方法:
看起来你正在做cesar-cipher加密,所以你可以尝试这样的事情:
strs = 'abcdefghijklmnopqrstuvwxyz' #use a string like this, instead of ord()
def shifttext(shift):
inp = raw_input('Input text here: ')
data = []
for i in inp: #iterate over the text not some list
if i.strip() and i in strs: # if the char is not a space ""
data.append(strs[(strs.index(i) + shift) % 26])
else:
data.append(i) #if space the simply append it to data
output = ''.join(data)
return output
输出:
In [2]: shifttext(3)
Input text here: how are you?
Out[2]: 'krz duh brx?'
In [3]: shifttext(3)
Input text here: Fine.
Out[3]: 'Flqh.'
strs [(strs.index(i)shift)%26]:上面的行表示在strs中找到字符i的索引,然后将移位值添加到它.现在,在最终值(索引移位)上应用&得到转移的指数.传递给strs [new_index]时,此移位索引会产生所需的移位字符.
内容总结
以上是互联网集市为您收集整理的Python中的文本转换功能全部内容,希望文章能够帮你解决Python中的文本转换功能所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。