Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete everything after a certain character in a string?

How would I delete everything after a certain character of a string in python? For example I have a string containing a file path and some extra characters. How would I delete everything after .zip? I've tried rsplit and split , but neither included the .zip when deleting extra characters.

Any suggestions?

like image 726
ThatGuyJay Avatar asked Jul 26 '13 21:07

ThatGuyJay


People also ask

How do you delete certain items from a string?

You can remove a character or multiple characters from a string using replace() or translate(). Both the replace() and translate() methods return the same outcome: a string without the characters you have specified.

How do I remove all characters from a string after a specific character C++?

Master C and Embedded C Programming- Learn as you go In this section, we will see how to remove some characters from a string in C++. In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed.


2 Answers

str.partition:

>>> s='abc.zip.blech'
>>> ''.join(s.partition('.zip')[0:2])
'abc.zip'
>>> s='abc.zip'
>>> ''.join(s.partition('.zip')[0:2])
'abc.zip'
>>> s='abc.py'
>>> ''.join(s.partition('.zip')[0:2])
'abc.py'
like image 28
Robᵩ Avatar answered Sep 30 '22 02:09

Robᵩ


Just take the first portion of the split, and add '.zip' back:

s = 'test.zip.zyz'
s = s.split('.zip', 1)[0] + '.zip'

Alternatively you could use slicing, here is a solution where you don't need to add '.zip' back to the result (the 4 comes from len('.zip')):

s = s[:s.index('.zip')+4]

Or another alternative with regular expressions:

import re
s = re.match(r'^.*?\.zip', s).group(0)
like image 78
Andrew Clark Avatar answered Sep 30 '22 03:09

Andrew Clark