> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Number of Segments in a String Python Solution

> Tested Python solution for LeetCode 434 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 434, [Easy](/catalog/easy). Topics: [String](/catalog/topics/string). [View on LeetCode](https://leetcode.com/problems/number-of-segments-in-a-string/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 434   # by problem number
lcpy gen -s number_of_segments_in_a_string   # by problem name
```

## Problem

Given a string `s`, return *the number of segments in the string*.

A **segment** is defined to be a contiguous sequence of **non-space characters**.

### Examples

```
Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
```

```
Input: s = "Hello"
Output: 1
```

### Constraints

* 0 \<= s.length \<= 300
* s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#\$%^&\*()\_+-=',.:".
* The only space character in s is ' '.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_segments_in_a_string/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_segments_in_a_string/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def count_segments(self, s: str) -> int:
        count = 0
        in_segment = False
        for ch in s:
            if ch != " " and not in_segment:
                count += 1
                in_segment = True
            elif ch == " ":
                in_segment = False
        return count
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.