iNTERFACEWARE Products Manual > Learning Center > Learning Python > Working With Strings > String Functions > Editing a String |
|
Looking for Iguana v.5 or v.6? Learn More or see the Help Center.
Python contains a number of functions that provide string editing capabilities. The most commonly used of these functions are strip(), lstrip(), rstrip(), replace() and zfill().
The strip() function removes unwanted leading and trailing characters from a string. By default, it removes unwanted whitespace characters (spaces and tabs):
To specify the unwanted leading and trailing characters to remove, include them as a parameter to strip():
In this example, strip() removes all leading and trailing * and = characters. It begins at the start of the string, and removes characters until it finds one that is not a * or =. It then repeats this process on the end of the string. lstrip() is identical to strip(), except that it only edits the start of the string; unwanted characters at the end of the string are not touched. Similarly, rstrip() behaves like strip() but only operates on the end of the string. The replace() function replaces all occurrences of one substring with another:
To specify a maximum number of replacements, supply this number as an additional parameter to replace():
The zfill() function pads a string with leading zeroes. This is useful if you are dealing with a string that contains numeric data but must be a specified length, such as a patient ID number:
The parameter to zfill() is the length of the string after leading zeroes are added. |