我在 python 中制作了一个简单的脚本,它使用 chr 和 ord 将 ASCII 表中的字母向上移动 5 个空格。见下文:
word = "python"
print 'Shifted 5 letters are: '
for letters in word:
print chr(ord(letters)+5),
输出是:
Shifted 5 letters is:
u ~ y m t s
输出很好,但是如何停止 for 循环在每个字母之间放置空格?
我在 python 中制作了一个简单的脚本,它使用 chr 和 ord 将 ASCII 表中的字母向上移动 5 个空格。见下文:
word = "python"
print 'Shifted 5 letters are: '
for letters in word:
print chr(ord(letters)+5),
输出是:
Shifted 5 letters is:
u ~ y m t s
输出很好,但是如何停止 for 循环在每个字母之间放置空格?
如果您不需要使用 for 循环,只需执行以下操作:
print ''.join([chr(ord(letter) + 5) for letter in word])
而不是整个循环。
print当您使用“魔术逗号”时,无法阻止 Python 2.x 的语句打印空格。
这是 Python 3.x 的print函数更灵活的部分原因,它使用关键字参数而不是魔术语法:
for letters in word:
print(chr(ord(letters)+5), end='')
如果你真的想要,你可以在 Python 2.x 中使用from __future__ import print_function(或使用第三方six库)获得相同的行为。
但是,通常,当您在print做自己想做的事情时遇到问题时,解决方案是首先格式化您的字符串,然后打印它。所以:
output = ''
for letters in word:
output += chr(ord(letters)+5)
print output
建立一个list字符串并在最后调用join,而不是重复附加到一个字符串,通常更pythonic(并且更快):
output = []
for letters in word:
output.append(chr(ord(letters)+5))
print ''.join(output)
您可以通过将循环转换为理解而不是语句来使其更简单(甚至更快) :
print ''.join(chr(ord(letters) + 5) for letters in word)
我不知道我是否得到了 100% 的要求,但这种解决方法返回了没有任何空格的字母:
def no_space(word) :
new_word = ""
for letter in word :
new_word += chr(ord(letter) + 5)
return new_word
然后调用函数:
no_space("python")
结果:'u~ymts'