How to replace custom tabs with spaces in a string, depend on the size of the tab?

前端 未结 12 2093
無奈伤痛
無奈伤痛 2021-01-17 15:13

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.

12条回答
  •  心在旅途
    2021-01-17 15:34

    if you have the requirement where you want to add n spaces instead of custom tab you can simply write below code. I have shown the implementation using two functions, each having different way to solve it.You can use any of the function!

    for eg. let the string be in the variable 'code' and 'x' be the size of tab

    code = "def add(x, y)\f\treturn x + y"
    x=4
    
    def convertTabs(code, x):
        temp=""
        for i in range(0,x):
            temp+=" "
        return code.replace("\t",temp) 
    
    def converTabs1(code,x):
        return code.replace("\t",x*" ")
    

    both the functions above will give the same value, but the second one is super awesome !

提交回复
热议问题