Skip to main content
 首页 » 编程设计

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

2025年02月15日8zhwl

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

这样按空格更改行
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    

注意事项:

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