More Ways To Manipulate Strings

There are a number of other useful commands for string manipulation. These include scan, format, string, and append. Two more string manipulation commands are regexp and regsub. Those two commands require a decent understanding of regular expressions, so I will hold off describing regexp and regsub until Chapter 6 (p. 135). Then, the commands will be much easier to understand.

The scan And format Commands

The scan and format commands extract and format substrings corresponding to low-level types such as integers, reals, and characters. scan and format are good at dealing with filling, padding, and generating unusual characters. These commands are analogous to sscanf and sprintf in the C language, and most of the C conventions are supported.

As an example, the following command assigns to x a string composed of a ^A immediately followed by "foo==1700.000000" (the number of zeros after the decimal point may differ on your system). The string is left-justified in an eight-character field.

set x [format "%1c%-8s==%f" 1 foo 17.0e2]

The first argument is a description of how to print the remaining arguments. The remaining arguments are substituted for the fields that begin with a "%“. In the example above, the "-" means “left justify” and the 8 is a minimum field width. The "c“, "s“, and "f" force the arguments to be treated as a character, a string, and a real number (f stands for float), respectively. The "==" is passed through literally since it does not ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.