简体   繁体   中英

Count occurrences of tab in python

I'm trying to count the number of tabs in a string, but it always gives me 0.

numbers = '1\\t2\\t3\\t4\\t5'

And I want to return 4. But:

numbers.count('\\t')

gives 0

  1. Your string does not have any tabs. A tab is represented as '\\t' , not as '\\\\t' . The latter is a backslash followed by a 't' .

  2. numbers.count('\\\\t') correctly reports 4.

  3. This is what you probably want:

     numbers = '1\\t2\\t3\\t4\\t5' numbers.count('\\t') # 4

Count number of spaces in the input string you provided and determine how many tabs that is according to your definition of a tab.

def calcTabs(numbers, tab):
    split_nums = numbers.split(",")
    num_tabs = []
    for elem in split_nums:
        space_ind = elem.count(' ')
        num_tabs.append(len(space_ind)/tab)

    return num_tabs

tab = 4 # number of spaces a tab equals
numbers = '1,3    4,5 6    7    8'

list_tabs = calcTabs(numbers, tab)
print(list_tabs)

Output:

[0.0, 1.0, 2.25] 

As can be seen this tells you the number of tabs (even with fractions if you have 2 tabs and a space for example in this case).


If you want just the number of tabs (as a whole number), you can use math.floor() to do so:

import math 

def calcTabs(numbers, tab):
    split_nums = numbers.split(",")
    num_tabs = []
    for elem in split_nums:
        space_ind = elem.count(' ')
        num_tabs.append(math.floor(space_ind/tab))

    return num_tabs

tab = 4 # number of spaces a tab equals
numbers = '1,3    4,5 6    7    8'

list_tabs = calcTabs(numbers, tab)
print(list_tabs)

Output:

[0, 1, 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM