如何使用2个参数拆分字符串 - python 3.5

时间:2017-04-04 18:48:40

标签: python-3.x

我想知道是否有办法使用.split()函数使用2个参数拆分字符串。

例如在数学方程中:

的x ^ 2 + 6X-9

是否可以使用+和 - 分割它? 所以它最终成为列表: [x ^ 2,6x,9]

3 个答案:

答案 0 :(得分:1)

这确实需要您提出问题

    public virtual IEnumerable NewLocation(PXAdapter adapter)
    {
            CustomerLocationMaint locationGraph = PXGraph.CreateInstance<CustomerLocationMaint>();
            Location locationRow = new Location();
            locationGraph.Location.Current = locationGraph.Location.Search<Location.locationID>(116, "ABARTENDE");
            locationGraph.Location.Insert(locationRow);
            throw new PXRedirectRequiredException(locationGraph, null) { Mode = PXBaseRedirectException.WindowMode.NewWindow };
                    return adapter.Get();
    }

学习正则表达式可能会帮助您完成您打算做的事情。在https://regex101.com/处使用 public virtual IEnumerable NewLocation(PXAdapter adapter) { CustomerLocationMaint locationGraph = PXGraph.CreateInstance<CustomerLocationMaint>(); Location locationRow = new Location(); locationRow.BAccountID = 109; //ABARTENDE locationRow.LocationID = 116; //MAIN locationGraph.Location.Insert(locationRow); throw new PXRedirectRequiredException(locationGraph, null) { Mode = PXBaseRedirectException.WindowMode.NewWindow }; return adapter.Get(); } 之类的内容,以更好地了解它们的工作方式。

答案 1 :(得分:0)

我认为您需要使用regx解决问题。

答案 2 :(得分:0)

由于.split()会返回一个列表,因此您必须再次遍历返回的列表。此函数(如下)允许您split任意次,但如另一个答案所述,您应该考虑使用re(正则表达式)模块。

from itertools import chain


def split_n_times(s, chars):
    if not chars:
        # Return a single-item list  if chars is empty
        return [s]

    lst = s.split(chars[0])
    for char in chars:
        # `chain` concatenates iterables
        lst = chain(*(item.split(char) for item in lst))

    return lst

正则表达式版本会短得多。