Skip to content Skip to sidebar Skip to footer

How To Delete Some Characters From A String By Matching Certain Character In Python

i am trying to delete certain portion of a string if a match found in the string as below string = 'Newyork, NY' I want to delete all the characters after the comma from the strin

Solution 1:

Use .split():

string = string.split(',', 1)[0]

We split the string on the comma once, to save python the work of splitting on more commas.

Alternatively, you can use .partition():

string = string.partition(',')[0]

Demo:

>>> 'Newyork, NY'.split(',', 1)[0]
'Newyork'>>> 'Newyork, NY'.partition(',')[0]
'Newyork'

.partition() is the faster method:

>>>import timeit>>>timeit.timeit("'one, two'.split(',', 1)[0]")
0.52929401397705078
>>>timeit.timeit("'one, two'.partition(',')[0]")
0.26499605178833008

Solution 2:

You can split the string with the delimiter ",":

string.split(",")[0]

Example:

'Newyork, NY'.split(",") # ['Newyork', ' NY']'Newyork, NY'.split(",")[0] # 'Newyork'

Solution 3:

Try this :

s = "this, is"m = s.index(',')
l = s[:m]

Solution 4:

A fwe options:

  • string[:string.index(",")]

    This will raise a ValueError if , cannot be found in the string. Here, we find the position of the character with .index then use slicing.

  • string.split(",")[0]

    The split function will give you a list of the substrings that were separated by ,, and you just take the first element of the list. This will work even if , is not present in the string (as there'd be nothing to split in that case, we'd have string.split(...) == [string])

Post a Comment for "How To Delete Some Characters From A String By Matching Certain Character In Python"