Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string.strip stripping too many characters [duplicate]

Tags:

I am using Python 3 to process file names, and this is my code:

name = 'movies.csv' table_name = name.strip(".csv") 

The expected value of table_name should be "movies" yet table_name keeps returning "movie".

Why is it doing this?

like image 933
Sihan Zheng Avatar asked Nov 30 '13 22:11

Sihan Zheng


1 Answers

strip() removes all the leading and trailing characters from the input string that match one of the characters in the parameter string:

>>> "abcdefabcdefabc".strip("cba") 'defabcdef' 

You want to use a regex: table_name = re.sub(r"\.csv$", "", name) or os.paths path manipulation functions:

>>> table_name, extension = os.path.splitext("movies.csv") >>> table_name 'movies' >>> extension '.csv' 
like image 185
Tim Pietzcker Avatar answered Sep 28 '22 04:09

Tim Pietzcker