How to Remove All Characters After a Specific Character in Python

How to remove all characters after a specific character in python?

Split on your separator at most once, and take the first piece:

sep = '...'
stripped = text.split(sep, 1)[0]

You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.

How to remove everything after specific character in csv

rstrip() just removes that one character from the right-side, if present -- it will also remove multiple ?s... e.g. if the string was 'abc???' it will return 'abc'.

If ? is not the final or rightmost character or characters, rstrip() is not going to do anything.

Instead do:

line2 = line.split('?')[0] 

which splits on any ?, and the [0] just takes the part before the first ? if there are multiple. Example:

In [43]: 'a?b?c?'.split('?')[0]
Out[43]: 'a'

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

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)

How to remove all characters after a certain character using Python 3

You can use re.sub

>>> mystr = "abcd (Read the tnc below!)"
>>>
>>> import re
>>> re.sub(r'\(.*', '', mystr)
'abcd '

To remove everything between parenthesis

>>> mystr = "abcd (Read the tnc below!)"
>>> re.sub(r'\(.*?\)', '', mystr)
'abcd '

In Python 2.4, how can I strip out characters after ';'?

I'd recommend saying

line.split(";")[0]

which will give you a string of all characters up to but not including the first ";" character. If no ";" character is present, then it will give you the entire line.

delete all characters after specific character, not character itself, in whole column, python

this solution convert int to string then search for first number different number from zero then take the partition you need (from begining to the position of the number different from zero) and convert it back to float. happy coding

df1['index']=[float(x[:x.find(x.split(".")[-1].replace("0","")[0])+1]) for x in list(map(str,df1['index']))]

How to remove substring after a specific character in a list of strings in Python

Here as a oneliner:

desired_list = [ s[:s.find(".",s.find(".")+1)] for s in current_list]

How to remove all characters before a specific character in Python?

Use re.sub. Just match all the chars upto I then replace the matched chars with I.

re.sub(r'^.*?I', 'I', stri)


Related Topics



Leave a reply



Submit