简体   繁体   English

如何通过匹配python中的某些字符从字符串中删除一些字符

[英]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 如果字符串中存在comma ,我想删除包含comma的字符串中comma之后的所有字符

Can anyone let me now how to do this . 任何人都可以让我现在如何做到这一点。

Use .split() : 使用.split()

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

We split the string on the comma once , to save python the work of splitting on more commas. 我们将字符串拆分为逗号一次 ,以便为python保存更多逗号分割的工作。

Alternatively, you can use .partition() : 或者,您可以使用.partition()

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

Demo: 演示:

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

.partition() is the faster method: .partition()是更快的方法:

>>> 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: 一个fwe选项:

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

    This will raise a ValueError if , cannot be found in the string. 这将引发ValueError ,如果,不能在字符串中被发现。 Here, we find the position of the character with .index then use slicing. 在这里,我们找到带有.index的角色的位置,然后使用切片。

  • 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. split函数将为您提供由,分隔的子字符串列表,您只需获取列表的第一个元素。 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] ) 这甚至会工作,如果,不存在字符串中(因为会是什么在这种情况下分裂,我们就会有string.split(...) == [string]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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