Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Power Query SplitTextByLengths Guide

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Deep Dive: Understanding the Lengths List
  4. Common Mistakes
  5. Tips for Efficiency
  6. Troubleshooting
  7. Frequently Asked Questions

The SplitTextByLengths function in Power Query (M language) is used to break a single text string into a list of multiple substrings based on a specific character count. Unlike the standard 'Split Column by Delimiter' feature found in the Power Query interface, which relies on finding a specific character like a comma or space, SplitTextByLengths allows you to segment data based on fixed character widths. This is essential for parsing legacy fixed-width files, mainframe data exports, or specific identification numbers where segments are defined by position rather than separators.

What You'll Need

  • Microsoft Excel or Power BI Desktop with the Power Query editor enabled.
  • A dataset containing text strings that need to be segmented by length.
  • Basic familiarity with the Power Query Advanced Editor to input custom M code.
  • Understanding of the M language syntax, specifically how lists and functions interact.

Step-by-Step

  1. Load Your Data: Open Excel or Power BI, navigate to the 'Data' tab, and select 'Get Data' to import your source file (CSV, Excel, or Text). Once the data is visible in the Power Query Editor window, ensure you have a column containing the text you wish to split. If your data is currently a single long string in one column, this is the correct starting point.
  2. Open the Advanced Editor: Because SplitTextByLengths is a functional M operation rather than a standard ribbon button, you must access the code level. Go to the 'Home' tab in the Power Query Editor and click on 'Advanced Editor'. This will reveal the script that governs your current transformation steps.
  3. Define the Function Logic: Within the Advanced Editor, you need to apply the function to your target column. The syntax follows the pattern: Text.SplitByLengths(text as text, lengths as list as any). Note that the second argument must be a list of numbers. For example, if you want to split a string every 5 characters, your code would use {5}. If you want to split a string into segments of 5, then 10, then 2, your list would be {5, 10, 2}.
  4. Implement the Custom Column: Instead of rewriting the entire script, a safer way to implement this is via the 'Add Column' tab. Click 'Custom Column'. In the formula box, enter the following structure: Text.SplitByLengths([YourColumnName], {5}). Replace [YourColumnName] with the actual name of your column and {5} with your desired length list.
  5. Expand the Resulting List: After clicking OK, you will see a new column containing the word 'List' in every cell. This is because the function returns a list of segments for each row. To turn these into actual data, click the two-way arrow icon in the header of the new 'Custom' column. You can choose to 'Expand to New Rows' (which creates new rows for every segment) or 'Extract Values' (which keeps one row but joins the segments with a delimiter like a comma).
  6. Finalize Data Types: Once the list is expanded, the new columns will likely have a 'General' or 'Any' data type. Click the data type icon next to the column header and select 'Text' to ensure the data is properly formatted for further analysis.

Deep Dive: Understanding the Lengths List

The power of SplitTextByLengths lies in the flexibility of the 'lengths' argument. In many data scenarios, segments are not uniform. For example, a legacy banking record might have a 10-character account number, followed by a 4-character transaction code, followed by a 12-character description. In a standard delimiter-based split, this would be impossible because there are no commas or tabs separating these fields. Using the SplitTextByLengths function, you would provide the list {10, 4, 12}. The function will consume the first 10 characters, then the next 4, and then the next 12. If the string is longer than the sum of your list, the remaining characters are often left in a final segment or handled according to the specific M engine version logic. If the string is shorter than the specified lengths, the function will simply return the available characters without erroring out, which makes it more robust than manual substring functions like Text.Middle.

Common Mistakes

One of the most frequent errors is providing a single integer instead of a list. Writing Text.SplitByLengths([Column], 5) will result in a syntax error because the function expects a list (enclosed in curly braces). Always ensure your length parameter is formatted as {5} or {5, 10, 15}. Another common mistake is attempting to use this function on a column that contains null values. If a row contains a null, the function will return an error for that specific row. To prevent this, you should either filter out nulls before the split or use a conditional statement such as if [Column] <> null then Text.SplitByLengths([Column], {5}) else null. Finally, users often forget that the output is a List object. If you do not perform the 'Expand' step mentioned in the Step-by-Step section, you will be unable to perform any mathematical or text-based operations on the individual segments because they are still wrapped inside a list container.

Tips for Efficiency

When working with very large datasets (hundreds of thousands of rows), expanding lists into new rows can significantly increase the memory footprint of your Power Query transformation. If you only need to extract one specific segment (for example, just the second segment of a split), do not expand the whole list. Instead, use the positional indexer. You can write a custom column formula like Text.SplitByLengths([Column], {5, 5}){1}. In M, lists are zero-indexed, so {1} will retrieve the second segment created by the split. This is much more performance-efficient than expanding all segments and then deleting the ones you don't need. Additionally, always check the total length of your source strings using Text.Length([Column]) before applying the split. If your lengths list does not account for the full length of the string, you may inadvertently lose data or find it tucked away in an unexpected final segment.

Troubleshooting

If your transformation fails, check the following in order:

  • Check for Data Type Mismatches: Ensure the column you are targeting is explicitly set to the 'Text' data type. If the column is set to 'Any' or 'Number', the function may fail to recognize the text methods. Use the 'Transform' tab to set the type to Text before adding the custom column.
  • Validate the List Syntax: Ensure your lengths are inside curly braces {}. A missing brace is the most common cause of the 'Expression.Error: We cannot convert the value... to type List' message.
  • Inspect for Non-Printable Characters: Sometimes, fixed-width files contain hidden characters like carriage returns (CR) or line feeds (LF) within the string. These characters count toward the length of the string. If your split seems 'off' by one or two characters, use the Text.Clean function on your source column before splitting to remove these invisible characters.
  • Error in Expansion: If you receive an error during the 'Expand to New Rows' step, it usually means there is a data type conflict in the column you are trying to expand. Try converting the source column to Text first, then performing the split.

Frequently Asked Questions

Can I use SplitTextByLengths with a variable length?

Yes, you can pass a field from another column as the list argument, provided that the field contains a list. However, most users use a static list of integers. If you want to split by a length that changes per row, you must ensure that the logic generating that length results in a list format.

Does this function handle spaces at the end of segments?

The function treats spaces as characters. If your fixed-width data uses spaces as padding (e.g., 'ABC '), the split will include those spaces in the resulting segments. You will likely need to follow the split with a 'Transform > Trim' step to remove leading or trailing whitespace from the new columns.

What is the difference between this and Text.Split?

Text.Split looks for a specific delimiter (like a semicolon) and splits whenever it finds that character. SplitTextByLengths ignores what the characters are and simply cuts the string at the specified intervals. Use Text.Split for delimited files and SplitTextByLengths for fixed-width files.

Will this function work in Power BI Service?

Yes, as long as the M code is valid and the data source is accessible via a gateway or cloud connection, the SplitTextByLengths function will execute correctly during the scheduled refresh in the Power BI Service.

How do I split a string into equal parts?

To split a string into equal parts of, say, 10 characters each, use {10} as your list. If you want to split a 30-character string into three 10-character parts, you can use {10, 10, 10} or simply {10} and then expand the list; the engine will continue to split by 10 until the string is exhausted.