如何用字符串中的空格替换自定义制表符,取决于制表符的大小? [英] How to replace custom tabs with spaces in a string, depend on the size of the tab?

查看:73
本文介绍了如何用字符串中的空格替换自定义制表符,取决于制表符的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 python 函数,它不使用任何模块,这些模块将采用带有制表符的字符串,并用适合输入制表位大小的空格替换制表符.它不能只是用 n 个空格替换所有大小为 n 的制表符,因为制表符可能是 1 到 n 个空格.我真的很困惑,所以如果有人能指出我正确的方向,我将不胜感激.

I'm trying to write a python function not using any modules that will take a string that has tabs and replace the tabs with spaces appropriate for an inputted tabstop size. It can't just replace all size-n tabs by n spaces though, since a tab could be 1 to n spaces. I'm really confused, so if anyone could just point me in the right direction I'd greatly appreciate it.

例如,如果制表位最初是 4 号:

For instance, if tabstop is size 4 originally:

123\t123 = 123 123 #one space in between

但改为制表位 5:

123\t123 = 123  123 #two spaces in between

我想我需要用空格填充字符串的末尾,直到 string%n==0 然后将它分块,但我现在很迷茫..

I think I need to pad the end of the string with spaces until string%n==0 and then chunk it, but I'm pretty lost at the moment..

推荐答案

既然你想要一个不使用任何外部模块的python函数,我认为你应该首先设计你函数的算法......

Since you wan't a python function that doesn't use any external module, I think you should design first the algorithm of your function...

我建议迭代字符串的每个字符;如果 char i 是制表符,则需要计算要插入多少个空格:下一个对齐"索引是 ((i/tabstop) + 1) * tabstop.所以你需要插入 ((i/tabstop) + 1) * tabstop - (i % tabstop).但更简单的方法是插入制表符直到对齐(即 i % tabstop == 0)

I would propose to iterate on every char of the string ; if char i is a tab, you need to compute how many spaces to insert : the next "aligned" index is ((i / tabstop) + 1) * tabstop. So you need to insert ((i / tabstop) + 1) * tabstop - (i % tabstop). But an easier way is to insert tabs until you are aligned (i.e. i % tabstop == 0)

def replace_tab(s, tabstop = 4):
  result = str()
  for c in s:
    if c == '\t':
      while (len(result) % tabstop != 0):
        result += ' ';
    else:
      result += c    
  return result

这篇关于如何用字符串中的空格替换自定义制表符,取决于制表符的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆