Search code examples
pythonfor-loopcounterstrip

Counting how many times a base function is being used, Python


I wanna be able to count how many times the strip function as well as how many white spaces are being removed in a for loop:

reproducible example:

df = pd.DataFrame({'words': ['hi', 'thanks ', 'for ', 'helping '],
                   'more_words': ['i ', ' have', 'been', 'stuck'],
                   'even_more_words': ['four ', ' ages', 'word' , 'more words']})

count = 0 
# striping white spaces
for col in df.columns:
        df[col] = df[col].str.strip()

print("I stripped this many blank spaces:", count)

The output should be 7, as it striped 7 white spaces

What is the simplest way to achieve this? Any hints or areas to look into would be greatly appreciated.


Solution

  • The simplest way is to store the original string length and then subtract the new length from it. The only mutation is the strip operation, so this should be correct.

    df = {'words': ['hi', 'thanks ', 'for ', 'helping '],
                       'more_words': ['i ', ' have', 'been', 'stuck'],
                       'even_more_words': ['four ', ' ages', 'word' , 'more words']}
    
    count = 0 
    # stripping white spaces
    for col in df:
        count += sum(len(x) for x in df[col])
        df[col] = [x.strip() for x in df[col]]
        count -= sum(len(x) for x in df[col])
    print("I stripped this many blank spaces:", count)
    

    This a more minimal example, without having to use Pandas, but the idea is the same.