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:
location = "XYZ Hospital and Treatment Center"
x = location[1]
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:
location = "XYZ Hospital and Treatment Center"
x = location[-2]
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:
location = "XYZ Hospital and Treatment Center"
x = location[1:3]
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:
location = "XYZ Hospital and Treatment Center"
x = location[:3] # this assigns "XYZ" to x
If you leave out the last index, the slice includes up to the end of the string:
location = "XYZ Hospital and Treatment Center"
x = location[17:] # this assigns "Treatment Center" to x
You can use negative indexes in slices:
location = "XYZ Hospital and Treatment Center"
# assign the last three characters of location to x
x = location[-3:] # this assigns "ter" to x
# assign everything except the last two characters of location to y
y = location[:-2] # this assigns "XYZ Hospital and Treatment Cent" to y
# assign the third-last and fourth-last characters of location to z
z = location[-4:-2] # this assigns "nt" to z
You can also use slices with lists. For example:
segmentlist = ["MSH", "EVN", "PID", "NK1", "PV1"]
x = segmentlist[1:3]
print x # this prints ['EVN', 'PID']