Python 从if条件传递到拆分函数的参数
上述字符串可能包含Python 从if条件传递到拆分函数的参数,python,Python,上述字符串可能包含.gds或.cdl扩展名。我想根据扩展名拆分字符串 这里介绍了如何将参数传递给split函数。(EX如果.gds以字符串形式存在,则应将其视为split(.gds”) 如果字符串中有.cdl,那么它应该得到拆分(“.cdl”))我认为您必须拆分if语句: string= "im fine.gds how are you" if '.gds' or '.cdl' in string : a=string.split("????????") 此外,您在中的声明不正确;
.gds
或.cdl
扩展名。我想根据扩展名拆分字符串
这里介绍了如何将参数传递给split函数。(EX如果.gds
以字符串形式存在,则应将其视为split(.gds”)
如果字符串中有
.cdl
,那么它应该得到拆分(“.cdl”)
)我认为您必须拆分if
语句:
string= "im fine.gds how are you"
if '.gds' or '.cdl' in string :
a=string.split("????????")
此外,您在中的声明不正确;应该是的
if '.gds' in string:
a = string.split('.gds')
elif '.cdl' in string:
a = string.split('.cdl')
else:
a = string # this is a fallback in case none of the patterns is in the string
请注意,此解决方案假定字符串中只有一个模式。如果两种模式可以出现在同一个字符串上,请参见Vikas的答案。使用正则表达式模块re
按pattern1
或pattern2
进行拆分
if '.gds' in string or '.cdl' in string:
例如:
import re
re.split('\.gds|\.cdl', your_string)
您可以尝试定义如下函数:
>>> re.split('\.gds|\.cdl', "im fine.gds how are you")
['im fine', ' how are you']
>>> re.split('\.gds|\.cdl', "im fine.cdl how are you")
['im fine', ' how are you']
>>> re.split('\.gds|\.cdl', "im fine.cdl how are.gds you")
['im fine', ' how are', ' you']
当然,您给出扩展的顺序很关键,因为您将在第一个扩展上进行拆分…您是否保证两个扩展中的一个会在那里
def split_on_extensions(string, *extensions):
for ext in extensions:
if ext in string:
return string.split(ext)
return string
如果您不确定它将在那里,您可以捕获在下一步中提出的停止迭代
:
a = next( string.split(v) for v in ('.gds','.cdl') if v in string )
标记被捕获到第一个反向引用中。regex
中的问号会使星形变懒,以确保它在第一个结束标记之前停止,而不是像贪婪的星形那样在最后一个结束标记之前停止
此正则表达式不能正确匹配嵌套在其内部的标记,如在onetwoone
中,另一个选项是使用BIF。这就是它的工作原理:
try:
a = next( string.split(v) for v in ('.gds','.cdl') if v in string )
except StopIteration:
a = string #????
将其放入一个小函数和您的集合中。您可以使用iter分离器:
sring= "im fine.gds how are you"
three_parts_of_sring = sring.partition('.gds')
>>> three_parts_of_sring
('im fine', '.gds', ' how are you')
语法中的对初学者不起作用。如果“.gds”和“.cdl”都在字符串中,您想怎么做?两个都分开?两个都没有?就其中一个?很好的解决方案。一般来说,对于这些简单的问题,我会尽量避免使用正则表达式,但是如果你有10个模式而不是2个模式,这是一个好主意。你甚至可以将扩展保持为一个iterable:ext=['gds','cdl']
然后:'|'。join(对于ext中的e来说是escape('.+e)
@HerrKaputt,是的,我也会尽量避免使用正则表达式。在本例中,它有一个优点,即如果字符串中出现了多个模式,则re.split将在所有匹配项上拆分。要在str.split中执行类似的操作,您必须在结果上迭代调用str.split。@Vikas,您是对的。从OP中,我立即假设最多会出现一种模式,但不清楚,这就是为什么我用指向你的指针更新了我的答案(并且也投了赞成票):)我不喜欢这个解决方案——它给出的答案与OP建议的使用split
相同,从结果中删除'.gds'
部分的额外开销(您必须将元组转换为列表,检测'.gds'
的位置,将其弹出,等等)。我也不必使用它,我只是想指出,还有另一个选项-如上所述。请避免使用名称“string”,因为它可能会与标准(并且不推荐使用)python模块“string”混淆
string= "im fine.gds how are you"
separators = ['.gds', '.cdl']
for separator in separators:
if separator in string:
a = string.split(separator)
break
else:
a = []