# Equivalent to pythons \`str.partition\` method?

**URL:** <https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952>\
**Category:** uncategorized\
**Created:** [November 6, 2021, 8:59pm UTC](https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952 "2021-11-06T20:59:20Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ethindp](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/ethindp/32/15953_2.png) [@Ethindp](https://users.rust-lang.org/u/Ethindp)\
**Post date:** [November 6, 2021, 8:59pm UTC](https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952/1 "2021-11-06T20:59:20Z")

</div>

So I'm trying to rewrite a parser in Python in Rust that uses `str.partition()` in Python. The Python code looks like:

```python
  for f in inputs:
    for line in f:
      line = line.partition('#')
      tokens = line[0].split()

```

I'm thinking an equivalent (and idiomatic) version might be something like:

```rust
for f in inputs.iter() {
    for line in f.lines() {
        let (line, old): (Vec<char>, Vec<char>) = line.chars().partition(|c| c == '#');
        let tokens = old.split(|c| c.is_whitespace()).collect::<Vec<_>>();

```

But I might be wrong, so I thought I'd ask (I've never ported Python programs to Rust -- at least ones like this, so I'm not sure how to get the same behavior idiomatically). Thoughts?

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [November 6, 2021, 9:20pm UTC](https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952/2 "2021-11-06T21:20:04Z")

</div>

## Equivalent to Python's `str.partition()` method in Rust

So, Python's `str.partition(sep)` is a _minor convenience wrapper_ around `.splitn(sep, 1)`.

Mainly, one could polyfill it as:

```Python
def partition(s: str, sep: str):
    if not sep:
        raise ValueError("Empty separator")
    (before, *mb_after) = s.splitn(sep, 1)
    return (before, *((sep, mb_after[0]) if mb_after else ("", "")))

```

Note how the core logic is still `.split()`: `str.partition()` tries to find a point in the string at which to split / cut the string in two parts.

In Rust, however, `Iterator::partition` does not do that. Instead, given a predicate, it shall dispatch each element of the iterator to either of the two collections / "buckets" it returns: the left "bucket" will contain the elements that matched (so just `'#'`s in your case), and the right bucket will contain the others).

So, if you want to implement `.partition()` in Rust, just rewrite the Python function above in Rust 🙂

```rust
fn partition<'s, 'sep> (s: &'s str, sep: &'sep str)
  -> (&'s str, &'sep str, &'s str)
{
    if sep.is_empty() {
        panic!("Empty separator");
    }
    let mut iter = s.splitn(sep, 1);
    let before = iter.next().unwrap();
    if let after = iter.next() {
        (before, sep, after)
    } else {
        (before, "", "")
    }
}

```

Although using "sentinel values (such as `""`) to signal an error / special case is not very idiomatic in Rust, where we have the wonderful `Option` `enum`:

```rust
fn partition<'s, 'sep> (s: &'s str, sep: &'sep str)
  -> (&'s str, Option<&'s str>)
{
    if sep.is_empty() {
        panic!("Empty separator");
    }
    let mut iter = s.splitn(sep, 1);
    (
        iter.next().unwrap(),
        iter.next(),
    )
}

```

EDIT: at that point we are very close to the signature of @steffahn's very aptly suggested `.split_once()` function 👌

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [November 6, 2021, 9:21pm UTC](https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952/3 "2021-11-06T21:21:00Z")

</div>

python's `partition` seems to be doing something entirely different, judging by the docs I could find, compared to Rust's `Iterator::partition`. For a better Rust-equivalent you could use e.g. [`str::split_once`](https://doc.rust-lang.org/std/primitive.str.html#method.split_once). Something like `line.split_once('#').unwrap_or(&line)` should give you the whole string if there is no `#` and the string up to (not including) the first `#` otherwise.

You could then proceed using the [`str::split_whitespace`](https://doc.rust-lang.org/std/primitive.str.html#method.split_whitespace) method

---

<div class="post-metadata">

**Author:** ![KillTheMule](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/killthemule/32/4748_2.png) [@KillTheMule](https://users.rust-lang.org/u/KillTheMule)\
**Post date:** [November 6, 2021, 9:43pm UTC](https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952/4 "2021-11-06T21:43:25Z")

</div>

So, deviating from the approach others seem to be taking, it looks to me like you 1) want to ignore everything after `#` on a line, and 2) split everything before it by whitespaces. Right?

[Here](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=b025936252833f87cdd9962f796400e3) is how I would do it

---

<div class="post-metadata">

**Author:** ![Ethindp](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/ethindp/32/15953_2.png) [@Ethindp](https://users.rust-lang.org/u/Ethindp)\
**Post date:** [November 7, 2021, 12:05am UTC](https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952/5 "2021-11-07T00:05:02Z")

</div>

Pretty sure this is what I intended to do, we'll see.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [February 5, 2022, 12:05am UTC](https://users.rust-lang.org/t/equivalent-to-pythons-str-partition-method/66952/6 "2022-02-05T00:05:42Z")

</div>

Closed on February 5, 2022, 12:05am UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
