galabl
galabl

Reputation: 63

Strip and split at same time in python


I'm trying to split and strip one string at same time.
I have a file D:\printLogs\newPrintLogs\4.txt and I want to split it that I get only 4.txt and than to strip the .txt and add in string + ".zpr" to get "4.zpr".
This is the code that I tryed to use:

name = str(logfile)
print ("File name: " + name.split('\\')[-1] + name.strip( '.txt' ))

But I get this output:

File name: 4.txtD:\printLogs\newPrintLogs\4

Upvotes: 2

Views: 9316

Answers (5)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You can split and rstrip:

print(s.rsplit("\\",1)[1].rstrip(".txt"))

But it may be safer to split on the .:

print(s.rsplit("\\",1)[1].rsplit(".",1)[0])

If you rstrip or strip you could end up removing more than just the .txt .

Upvotes: 0

Dunes
Dunes

Reputation: 40693

For python 3.4 or later:

import pathlib

name = r"D:\printLogs\newPrintLogs\4.txt"
stem = pathlib.Path(name).stem
print(stem) # prints 4

Upvotes: 0

galabl
galabl

Reputation: 63

Thank you all for your solutions it helped me but at first I didn't explained question right.
I founded solution for my problem

name = str(logfile)
print ("Part name: " + name.split('\\')[-1].replace('.txt','.zpr'))

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121854

Don't use stripping and splitting.

First of all, stripping removes all characters from a set, you are removing all 't', 'x' and '.' characters from the start and end of your string, regardless of order:

>>> 'tttx.foox'.strip('.txt')
'foo'
>>> 'tttx.foox'.strip('xt.')
'foo'

Secondly, Python offers you the os.path module for handling paths in a cross-platform and consistent manner:

basename = os.path.basename(logfile)
if basename.endswith('.txt'):
    basename = os.path.splitext(basename)[0]

You can drop the str.endswith() test if you just want to remove any extension:

basename = os.path.splitext(os.path.basename(logfile))[0]

Demo:

>>> import os.path
>>> logfile = r'D:\printLogs\newPrintLogs\4.txt'
>>> os.path.splitext(os.path.basename(logfile))[0]
'4'

Upvotes: 6

TigerhawkT3
TigerhawkT3

Reputation: 49318

You're adding too much there. This is all you need:

print ("File name: " + name.split('\\')[-1].strip( '.txt' ))

Better yet, use the os module:

>>> import os
>>> os.path.splitext(os.path.basename(r'D:\printLogs\newPrintLogs\4.txt'))[0]
'4'

Or, split up among several steps, with occasional feedback:

>>> import os
>>> name = r'D:\printLogs\newPrintLogs\4.txt'
>>> basename = os.path.basename(name)
>>> basename
'4.txt'
>>> splitname = os.path.splitext(basename)
>>> splitname
('4', '.txt')
>>> splitname[0]
'4'

Upvotes: 6

Related Questions