简体   繁体   中英

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 string including comma , if comma is present in the string

Can anyone let me now how to do this .

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

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

string.split(",")[0]

Example:

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

Try this :

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

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] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM