Python string.strip stripping too many characters [duplicate]
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.path
s path manipulation functions:
>>> table_name, extension = os.path.splitext("movies.csv")
>>> table_name
'movies'
>>> extension
'.csv'
Maybe a bit late, but for those reading this in the future, there is a lazy way that appears to work fine too (assuming all the files from which you want to retrieve the names are CSV files):
if name.endswith('.csv'):
table_name = name.rstrip("csv").rstrip(".")
As said in other solutions, the strip()
method removes all the leading/trailing characters that match those inside the parentheses. Therefore, the idea in this approach is to:
- Remove the
csv
extension - since there is a.
we knowrstrip()
will stop searching there. This will leave us with themovies.
string. - Remove the
.
from themovies.
string - therstrip()
will only look for trailing dots.
Why rstrip()
: Since we know that the text to be removed is in the end of the string, we can specify rstrip
for better control (i.e. to avoid unintentionally removing any eventual leading c, s or v characters)