Written and maintained by CASRAI Editorial Board
Published
On this page
The STRIP function in SAS removes both leading and trailing blanks from a character string or variable, returning a trimmed character value while preserving all spaces located between words. Unlike the older TRIM function which only deletes trailing blanks, the STRIP function combines the operations of left-alignment and right-trimming into a single optimized routine for data cleaning, string concatenation, and clinical research dataset standardization.
What the STRIP function in SAS is used for in research
In empirical and quantitative research, data consistency is the foundation of reproducible analysis. Researchers working across clinical trials, epidemiologic cohorts, health services registries, and survey databases frequently ingest character data originating from heterogeneous electronic medical records, web portals, or legacy database exports. A pervasive challenge in these datasets is the presence of spurious whitespace padding around subject identifiers, diagnostic codes, specimen lot numbers, and categorical responses.
The storage architecture of the SAS System handles character variables through fixed-width allocations. When a character column is defined with a format such as $20., SAS reserves exactly 20 bytes of memory. If an incoming data value contains only 8 characters, SAS automatically pads the remaining 12 bytes with trailing blanks. Furthermore, values derived from formatted numeric conversions or fixed-width text files frequently arrive with leading blanks. These extraneous blank spaces create severe technical problems throughout quantitative research pipelines:
- Record linkage and table joins: In merge procedures and SQL operations, exact character matches depend on every single byte. An identifier stored as ‘SUBJ_101’ will fail to match ‘ SUBJ_101’ or ‘SUBJ_101 ‘, resulting in unmatched records, dropped participants, and corrupted cohort merges.
- Categorical stratification and frequency tabulations: Procedures such as PROC FREQ and statistical modeling routines treat values with whitespace differences as distinct nominal categories. For instance, ‘Treatment’ and ‘ Treatment’ are parsed as separate experimental arms, inflating degrees of freedom and biasing statistical estimates.
- Composite key synthesis: Generating composite study keys by concatenating study center codes, visit numbers, and subject identifiers using standard operators produces unwanted internal padding unless each token is stripped first.
- Standardized metadata compliance: Regulatory data submissions, such as the Clinical Data Interchange Standards Consortium (CDISC) Study Data Tabulation Model (SDTM), mandate strict conformance to standardized terminologies without leading or trailing spaces.
Applying rigorous character sanitation through functions like STRIP is an essential component of systematic data curation, ensuring that data pipelines retain integrity across all analysis stages.
How to install or access SAS
Institutional and academic researchers utilize several sanctioned environments to access the SAS System and execute character processing routines:
- SAS OnDemand for Academics: A cloud-hosted environment made available by SAS Institute for non-commercial academic research and instructional coursework. Users register an official SAS profile, upload project files to allocated cloud storage, and write SAS programs within the web-based SAS Studio interface without local software installation.
- SAS Viya: The modern cloud-native analytics architecture deployed on private enterprise servers or commercial cloud infrastructure. Researchers interact with SAS Viya through SAS Studio, submitting DATA steps and Cloud Analytic Services actions for high-throughput parallel data manipulation.
- SAS 9.4 Desktop and Enterprise Server: Workstation and client-server installations deployed across institutional servers, accessed through the SAS Display Manager, SAS Enterprise Guide, or direct terminal command-line batch execution.
To execute SAS scripts in batch mode on a server or local terminal, researchers use the official command-line invocation syntax:
sas -nodms -noterminal -sysin clean_strings.sas -log clean_strings.log
All code examples below run identically across SAS 9.4, SAS Viya, and SAS OnDemand for Academics.
How to strip leading and trailing blanks in SAS step by step
Stripping whitespace in a SAS DATA step requires careful attention to variable length declarations and function behavior. Follow this five-step procedure to reliably sanitize character variables:
- Inspect variable lengths and identify padding: Before applying string cleaning, check both the visual content and the physical length of raw character fields using the LENGTH and LENGTHN functions.
- Declare explicit target variable lengths: Always include an explicit LENGTH statement for newly created character variables before the assignment. If no length is declared, SAS defaults to assigning the newly created variable the same storage length as the source argument, which immediately repads the value with trailing spaces upon dataset write.
- Apply the STRIP function in an assignment statement: Pass the raw character variable, expression, or literal string as the single argument to STRIP.
- Incorporate STRIP into concatenation pipelines: When assembling multi-part strings, apply STRIP to each constituent element before joining them with the concatenation operator, or use dedicated concatenation routines.
- Verify output datasets with bounded printing: Output the transformed variables to a SAS dataset and verify the absence of spaces using bounded character delimiters.
The following self-contained SAS program demonstrates the complete end-to-end data cleansing workflow on simulated clinical registry records:
/* Step-by-step string sanitation in a SAS DATA step */
options nodate pageno=1 ls=90;
data clinical_raw;
infile datalines truncover;
input raw_id $char12. raw_site $char10. raw_arm $char15.;
datalines;
PT_001 SITE_A Active
PT_002 SITE_B Placebo
PT_003 SITE_A Active
;
run;
data clinical_clean;
set clinical_raw;
/* Step 2: Explicitly declare target variable lengths */
length clean_id $8 clean_site $6 clean_arm $10 composite_key $20;
/* Step 3: Apply the STRIP function */
clean_id = strip(raw_id);
clean_site = strip(raw_site);
clean_arm = strip(raw_arm);
/* Step 4: Concatenate stripped tokens into a composite identifier */
composite_key = strip(clean_site) || '-' || strip(clean_id);
/* Calculate lengths to confirm space elimination */
len_raw_id = lengthn(raw_id);
len_clean_id = lengthn(clean_id);
run;
/* Step 5: Verify bounded output */
proc print data=clinical_clean noobs;
var raw_id clean_id composite_key len_raw_id len_clean_id;
run;
In this workflow, the raw variable values arrived with uneven leading blanks and right-padded spaces. By passing raw_id into strip(), leading spaces are discarded immediately. Furthermore, for string extraction and pattern matching tasks where specific byte positions must be isolated, researchers routinely combine STRIP with routines such as the SAS substring function and the SAS SUBSTRN function.
How to read the output
Interpreting the output of string operations in SAS requires understanding how SAS reports data in the execution log and in output tables. When running the DATA step program above, review the SAS Log first for operational metrics:
NOTE: There were 3 observations read from the data set WORK.CLINICAL_RAW.
NOTE: The data set WORK.CLINICAL_CLEAN has 3 observations and 8 variables.
NOTE: DATA statement used (Total process time):
real time 0.01 seconds
cpu time 0.01 seconds
A successful log verifies that observations passed through the DATA step without numeric-to-character conversion notes or string truncation warnings. Next, examine the tabular output generated by PROC PRINT:
Obs raw_id clean_id composite_key len_raw_id len_clean_id
1 PT_001 PT_001 SITE_A-PT_001 8 6
2 PT_002 PT_002 SITE_B-PT_002 9 6
3 PT_003 PT_003 SITE_A-PT_003 8 6
To correctly interpret these columns, researchers must distinguish three distinct concepts of string measurement in SAS:
- Storage length (LENGTHC): The total fixed byte footprint allocated to the variable in the dataset header. In clinical_clean, clean_id has a storage length of 8 bytes regardless of how many characters the value occupies.
- Content length (LENGTH): The position of the rightmost non-blank character. For non-empty strings, LENGTH measures the ending character. However, if a string is completely blank, LENGTH returns 1.
- True content length (LENGTHN): The exact count of characters excluding trailing spaces. When a string is blank or null, LENGTHN returns 0, providing the most accurate metric for validation scripts.
Notice in the output table that len_raw_id was 8 or 9 due to the position of the final character following leading spaces, whereas len_clean_id is exactly 6 characters across all rows. When character values contain numeric codes that must participate in statistical calculations, researchers feed the stripped character output into the INPUT function, as documented in the guide to convert character to numeric in SAS.
Troubleshooting the STRIP function in SAS
Even experienced SAS analysts encounter edge cases when cleaning text variables. Here are the most common technical traps and proven diagnostic solutions:
- The fixed-length repadding trap: A frequent complaint is that after executing
x = strip(y);, the variable x still contains trailing spaces in the dataset viewer. This occurs because SAS character variables in disk tables have fixed lengths. If variable x is allocated 20 bytes and the stripped string is only 5 bytes, SAS fills the remaining 15 bytes with blank padding upon storage. Solution: Understand that the trailing blanks reside in the container, not the value. When writing to delimited text files (CSV), use the:colon modifier or thedlmoption in a data export step so that SAS trims trailing blanks during export. - Inter-word blanks remaining untouched: The STRIP function removes spaces strictly from the beginning and end of a string. If an address contains multiple irregular spaces between words (such as ‘123 Main Street’), STRIP leaves all internal spaces intact. Solution: To compress multiple consecutive spaces between words down to a single space, wrap the variable in the COMPBL function:
clean_text = strip(compbl(raw_text));. If all spaces must be removed entirely, use COMPRESS instead. - Automatic numeric conversion warnings: Passing a numeric variable directly into STRIP (e.g.,
val = strip(numeric_code);) triggers an automatic type conversion. SAS converts the number using the BEST12. format, which right-aligns the number and writes a conversion note to the log. Solution: Explicitly convert the numeric variable with the PUT function before stripping:val = strip(put(numeric_code, best12.));. - Non-breaking spaces and invisible characters: Text imported from HTML tables, web forms, or Microsoft Word documents frequently contains non-breaking spaces (ASCII 160, hex ‘A0’x) or carriage return characters. The STRIP function recognizes only standard ASCII blanks (hex ’20’x). Non-breaking spaces will remain intact at the beginning or end of the string. Solution: Strip non-standard whitespace characters using the COMPRESS function with character modifiers or hex literals:
clean_val = strip(compress(raw_val, 'A0'x));. - Processing hundreds of variables simultaneously: In epidemiological cohort datasets with hundreds of questionnaire items, writing individual STRIP statements for every variable is inefficient and prone to omission. Solution: Iterate over all character variables in a single pass using a SAS character array and a DO loop, leveraging the techniques detailed in the SAS array programming reference.
/* Bulk stripping of all character variables via an array */
data survey_cleaned;
set survey_raw;
array char_vars[*] _character_;
do i = 1 to dim(char_vars);
char_vars[i] = strip(char_vars[i]);
end;
drop i;
run;
Free alternatives to SAS for string stripping
Quantitative researchers who transition between institutional SAS installations and open-source computational environments frequently require equivalent string trimming routines. The table below details free, open-source programming alternatives to SAS for removing leading and trailing whitespace:
| Tool and Language | Function or Syntax | Trims Leading | Trims Trailing | Preserves Inter-Word Spaces | Execution Paradigm |
|---|---|---|---|---|---|
| R (Base) | trimws(x, which = 'both') |
Yes | Yes | Yes | Vectorized native C implementation |
| R (stringr / stringi) | stringr::str_trim(x, side = 'both') |
Yes | Yes | Yes | ICU-backed Unicode whitespace stripping |
| Python (Standard Library) | x.strip() |
Yes | Yes | Yes | Dynamic string object method |
| Python (pandas) | series.str.strip() |
Yes | Yes | Yes | Vectorized Series string accessor |
| GNU Octave | strtrim(x) |
Yes | Yes | Yes | Matrix/cell array character trimming |
| Julia (Base) | strip(x) |
Yes | Yes | Yes | Type-stable high-performance JIT routine |
| SQL (PostgreSQL / SQLite) | TRIM(BOTH FROM col) |
Yes | Yes | Yes | Relational database engine query expression |
A critical operational difference between SAS and modern open-source languages like R and Python is string memory management. In R and Python, character strings have dynamic lengths: trimming whitespace shrinks the physical memory footprint of the string object immediately. In contrast, SAS maintains fixed-width character buffers in traditional datasets. When preparing data for archival deposit or cross-platform data exchange, open-source pipelines eliminate the need for fixed column length adjustments.
The data table below compares the functional properties, return lengths, and concatenation behaviors of SAS space-cleaning routines.
Frequently asked questions
What is the difference between TRIM and STRIP in SAS?
The primary difference between TRIM and STRIP in SAS is the handling of leading whitespace. The TRIM function deletes only trailing blanks from the end of a character string, leaving all leading blanks at the beginning intact. In contrast, the STRIP function deletes both leading and trailing blanks simultaneously. Additionally, when passed a string that consists entirely of blank spaces, TRIM returns a single blank space (length 1), whereas STRIP returns a null string with a length of zero.
Does STRIP remove spaces between words?
No, the STRIP function does not remove spaces located between words. It operates strictly on the outer boundaries of the string, removing leading whitespace before the first non-blank character and trailing whitespace after the final non-blank character. To remove all spaces everywhere in a string, use the COMPRESS function without arguments. To collapse multiple consecutive spaces between words into a single blank space, use the COMPBL function.
How does STRIP affect variable lengths in a DATA step?
Assigning the result of STRIP to a variable in a SAS DATA step does not automatically alter the fixed storage length allocated to that variable in the dataset definition. If a variable is defined as having a length of 20 bytes and the stripped string contains only 6 characters, SAS writes the 6 characters to the column and right-pads the remaining 14 bytes with blank spaces. To manage storage footprint, researchers must declare a shorter target variable length using an explicit LENGTH statement prior to the STRIP assignment.
What does the STRIP function return for an all-blank string?
When the argument passed to the STRIP function consists entirely of spaces or is empty, STRIP returns a string with a length of zero. This behavior matches the TRIMN function and contrasts with the standard TRIM function, which returns a single blank character. You can verify this length in SAS programs using the LENGTHN function, which returns 0 for stripped blank strings.
When should you use STRIP instead of COMPRESS in SAS?
Use the STRIP function when cleaning text values that contain legitimate internal spaces, such as person names, clinical narrative notes, street addresses, or geographic titles. In these scenarios, leading and trailing blanks are accidental artifacts of data entry or fixed-column imports, but inter-word spaces must be preserved. Use the COMPRESS function when removing all whitespace from alphanumeric identifiers, such as social security numbers, vehicle identification numbers, or telephone records.
Can the STRIP function be used in PROC SQL?
Yes, the STRIP function is fully supported within PROC SQL query expressions. Researchers frequently apply STRIP inside WHERE clauses, ON join conditions, and SELECT statements to ensure that table merges and grouping operations do not fail due to extraneous padding. For example, writing on strip(a.patient_id) = strip(b.patient_id) eliminates mismatched joins caused by inconsistent leading or trailing blanks between disparate source tables.
Sources
- SAS Institute: STRIP Function (SAS 9.2 Language Reference: Dictionary), checked 2026-11-19
- SAS Institute: TRIM Function (SAS 9.2 Language Reference: Dictionary), checked 2026-11-19
- SAS Institute: COMPRESS Function (SAS 9.2 Language Reference: Dictionary), checked 2026-11-19
- SAS Institute: CATS Function (SAS 9.2 Language Reference: Dictionary), checked 2026-11-19
- ListenData: STRIP Function in SAS : Remove Spaces from String, checked 2026-11-19
- UCLA Statistical Consulting: How can I get rid of extra spaces in a string variable?, checked 2026-11-19
Data: Comparison of SAS Character Trimming and String Cleaning Functions
Functional matrix evaluating SAS string sanitation functions across whitespace removal scope, blank string return length, execution profile, and concatenation integration based on SAS Institute 9.2 documentation and UCLA OARC computing standards.
| Function Name | Leading Blanks Removed | Trailing Blanks Removed | Inter-Word Blanks Removed | Blank Input Return Length (characters) | Execution Profile | Concatenation Role |
|---|---|---|---|---|---|---|
| STRIP | Yes | Yes | Preserved | 0 | Native C routine executing faster than nested TRIMN(LEFT()) | Manual join with || operator |
| TRIM | No | Yes | Preserved | 1 | Legacy string trimming routine | Preserves leading blanks in joins |
| TRIMN | No | Yes | Preserved | 0 | Zero-length variant of TRIM | Eliminates single blank return on empty input |
| LEFT | Yes | Shifted to end | Preserved | 1 | Left-alignment buffer shift | Pads trailing spaces up to declared length |
| COMPRESS | Yes | Yes | All removed | 0 | Byte-scanning deletion with optional character modifiers | Removes all whitespace by default |
| COMPBL | No | No | Collapsed to single space | 1 | Multi-space buffer normalization | Standardizes variable spacing between words |
| CATS | Yes | Yes | Preserved | 0 | Integrated multi-argument stripping and concatenation | Strips all arguments and joins them |
| CATX | Yes | Yes | Preserved | 0 | Delimited multi-argument stripping and concatenation | Strips all arguments and inserts delimiter |
Sources
- SAS Institute: STRIP Function (accessed 2026-11-19)
- SAS Institute: TRIM Function (accessed 2026-11-19)
- SAS Institute: COMPRESS Function (accessed 2026-11-19)
- SAS Institute: CATS Function (accessed 2026-11-19)
- ListenData: STRIP Function in SAS (accessed 2026-11-19)
- UCLA OARC Stats FAQ (accessed 2026-11-19)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







