How to split by comma and strip white spaces in Python?

Use list comprehension — simpler, and just as easy to read as a for loop. my_string = “blah, lots , of , spaces, here ” result = [x.strip() for x in my_string.split(‘,’)] # result is [“blah”, “lots”, “of”, “spaces”, “here”] See: Python docs on List Comprehension A good 2 second explanation of list comprehension.

String.strip() in Python

If you can comment out code and your program still works, then yes, that code was optional. .strip() with no arguments (or None as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn’t do any harm, and allows your program to deal … Read more

Removing leading zeros before passing a shell variable to another command

You don’t need to use sed or another external utility. Here are a couple of ways Bash can strip the leading zeros for you. iptables -t nat -I POSTROUTING -s “10.$machinetype.$((10#$machinenumber)).0/24” -j MASQUERADE The $(()) sets up an arithmetic context and the 10# converts the number from base 10 to base 10 causing any leading … Read more

Best way to automatically remove comments from PHP code

I’d use tokenizer. Here’s my solution. It should work on both PHP 4 and 5: $fileStr = file_get_contents(‘path/to/file’); $newStr=””; $commentTokens = array(T_COMMENT); if (defined(‘T_DOC_COMMENT’)) { $commentTokens[] = T_DOC_COMMENT; // PHP 5 } if (defined(‘T_ML_COMMENT’)) { $commentTokens[] = T_ML_COMMENT; // PHP 4 } $tokens = token_get_all($fileStr); foreach ($tokens as $token) { if (is_array($token)) { if (in_array($token[0], … Read more

python: rstrip one exact string, respecting order

You’re using wrong method. Use str.replace instead: >>> “Boat.txt”.replace(“.txt”, “”) ‘Boat’ NOTE: str.replace will replace anywhere in the string. >>> “Boat.txt.txt”.replace(“.txt”, “”) ‘Boat’ To remove the last trailing .txt only, you can use regular expression: >>> import re >>> re.sub(r”\.txt$”, “”, “Boat.txt.txt”) ‘Boat.txt’ If you want filename without extension, os.path.splitext is more appropriate: >>> os.path.splitext(“Boat.txt”) … Read more

Vim run autocmd on all filetypes EXCEPT

*.rb isn’t a filetype. It’s a file pattern. ruby is the filetype and could even be set on files that don’t have a .rb extension. So, what you most likely want is a function that your autocmd calls to both check for filetypes which shouldn’t be acted on and strips the whitespace. fun! StripTrailingWhitespace() ” … Read more

tech