python - 如何返回垂直对齐的文本(python3)

标签 python string python-3.x

我是编程初学者。 我正在创建返回排除非字母数字的垂直对齐文本的代码。它也应该像

这样按空格更改行
H W
e o
l r
l l
o d

我的代码在这里。 我可以垂直显示文本。 但是这个函数不返回。 那么我该如何编辑它以返回垂直文本? 如果您能详细解释一下,我们将不胜感激。

from itertools import zip_longest

def transposition(string):
  new_text = str()
  for i in string:
    x = i.isalpha()

    if x == False:
        i = ' '

    new_text += i

for y in zip_longest(*new_text.split(), fillvalue=' '):
    print (' '.join(y))

transposition("Hello, World")

最佳答案

如果我理解你的问题,你想要一个函数,它接受一个字符串,比如 "hello world",并返回一个字符串,比如 "h w\ne o\nl r\n"

如果是这样,我认为您基本上就在那里:

from itertools import zip_longest
import re

def transposition(string):

    clean_str = re.sub('[^\w]', ' ', string)
    return '\n'.join(
        ' '.join(row)
        for row in zip_longest(*clean_str.split(), fillvalue=' '))

print(transposition("Hello, World... how are you?"))

>> H W h a y
>> e o o r o
>> l r w e u
>> l l   
>> o d   

注意事项:

  • 我会养成使用正则表达式进行任何字符串操作的习惯。
  • 永远不要与TrueFalse 进行比较,只需比较if x:if not x: .
  • ' '.join(row) for row in ... 是一个 generator expression您可以将其传递给任何采用可迭代对象的函数。

关于python - 如何返回垂直对齐的文本(python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42398307/

相关文章:

python - Pymongo:bson.errors.InvalidDocument:无法编码对象:<pymongo.cursor.Cursor object at 0xc61990>

c - %g 浮点表示的最大字符串长度是多少?

python - 在哪里可以找到 Python 中可能的异常列表?

python - 使用日期作为输出文件中的索引

python - 使用 python 将文本文件解析为矩阵

python - 网站更改代码后网络爬虫抛出错误

python - 如何使用递归多次划分数字并跟踪迭代?

python - Vector2 乘法导致 python 中的段错误

java - 字符串中的数字频率

string - Dart/Flutter - 验证 URL 的字符串