iNTERFACEWARE Products Manual > Learning Center > Learning Python > Working With Strings > String Indexing and Slices |
|
Looking for Iguana v.5 or v.6? Learn More or see the Help Center.
You can use an index to copy a single character from a string. Indexes in strings work the same way they do in lists. Here is an example of code that copies a single character:
Here, the index 1 refers to the second character of the string, not the first, as indexing always starts from zero. This means that the second character of "XYZ Hospital and Treatment Center", Y, is assigned to the variable x. If your index is a negative number, indexing starts from the end of the string. For example, the following code assigns the second-last character of a string to a variable:
The second-last character of this string is e, which is assigned to x. Python also allows you to make a copy of part of a string. This copy, called a slice, is itself a string; it can be assigned to a variable or used anywhere a string can be used. A slice is specified by two indexes: an index representing the start of the slice, and an index representing the end of the slice. The two indexes are separated by a colon (:). For example:
In this example, [1:3] indicates that copying is to start at index 1 of the string and stop at index 3. This means that the second and third characters of location are copied, and the string YZ is assigned to x. In general, in slice [a:b], the characters from index a to index b-1 are copied; the character at index b is not copied. If you leave out the first index, the slice starts at the beginning of the string:
If you leave out the last index, the slice includes up to the end of the string:
You can use negative indexes in slices:
|