Python. Strings. Access by indexes. Slices. Get a fragment of a string. Examples




Strings. Access by indexes. Slices. Get a fragment of a string. Examples


Contents


Search other websites:

1. Ways to get string fragments

In Python, string fragments can be obtained in one of three ways:

  • indexing operation. This way you get one character in a string;
  • the operation of assigning a slice to a string. In this way, you can get either a single character or a fragment of a string;
  • using the functions of the standard Python library.

 

2. Indexing operation. Getting a character from the beginning and end of a string

In Python, using the indexing operation, you can get a specific character in a string. In general, the indexing operation is as follows

[index]

here index is the position of the character to be read from the string.

If the value is index≥0 (positive value), then the string is processed from its beginning. With positive indexing, the first element of the string has an offset of 0.
If index <0 (negative value), then the string is processed from the end. With negative indexing, the first of the end elements has an offset of -1.

Figure 1 shows an example of index numbering for some string S.

Python. Strings. Positive and negative indexing

Figure 1. Positive and negative indexing

In the example shown in the figure, the symbol b can be accessed in one of two ways:

c1 = S[1] # positive indexing, c1 = 'b'
c2 = S[-5] # negative indexing, c2 = 'b'

Example.

# Strings
# Positive and negative indexing

# Given string
s = "Hello world"

# Get character from beginning of string
c_begin = s[3] # c_begin = l
print('c_begin = ', c_begin)

# Get character from end of string
c_end = s[-3] # c_end = r
print('c_end = ', c_end)

The result of the program

c_begin = l
c_end = r

 

3. What is a slice? Types of slices when working with strings

A slice is a form of parsing that allows you to pull out fragments of strings (substrings) in one action. Using slices allows you to get substrings in a convenient way. There are two types of row slice assignment operations:

  • slices of the form [:]. In this case, two boundaries are indicated, separated by a symbol : (colon);
  • extended slice [::]. In this case, three boundaries are indicated, separated by a symbol : (colon).

 

4. Operation substring extraction with two boundaries [:].Ways to get a substring. Examples

When working with strings, the following slicing assignment forms can be distinguished, in which two boundaries are specified:

  • [i:j] – both boundaries i, j are set explicitly;
  • [:j] – the first boundary is absent;
  • [i:] – the second boundary is absent;
  • [:] – both boundaries are missing.


 

4.1. The form S[i : j]

In this case, the substring is pulled from index i to index j-1 inclusive from string S. Figure 2 shows an example of pulling substrings.

Python. Strings. Slices. Pulling substrings from string

Figure 2. Pulling substrings S2, S3, S4 from string S. Characters with indices 2, 3, 4 are pulled

 

4.2. The form S[ : j]

In this form, the first index is not indicated. This means that the substring is pulled from the beginning of the string (positive offset 0) to index j-1. Figure 3 shows an example of this slice.

Python. Strings. Slices. Pulling substrings from string

Figure 3. Pulling substrings from string S

 

4.3. The form S[i : ]

With this form, the second index is missing. This form pull out the elements of the string from position i to the end of the string. Figure 4 shows an example of this slice.

Python. Strings. Slices. Pulling substrings from a string

Figure 4. Pulling substrings from a string

 

4.4. The form S[ : ]

This form pulls the items of the string from the beginning of the string to the end of the string. In this way, you can get a shallow copy of a string that contains the same value but is located in a different area of memory.

Example.

# Assigning a slice of type [:]
S = 'abcdef'
S2 = S[:] # S2 = 'abcdef' - located in another memory area

 

5. Extended operation of pulling substring [::]. Ways to get a substring. Examples

The extended operation of pulling the substring [i:j:k] (slice) has three boundaries. The third boundary k defines the step by index. The value of step k is added to the position of each item that is pulled from the string. The value of k is optional. The default value is k=1.

Regarding the value of k, the following features can be distinguished:

  • if k≥0, then the string is considered from beginning to end (from left to right);
  • if k<0, then the string is considered from end to beginning (from right to left).

The following extended forms of pulling a substring are distinguished:

  • [i : j : k] – the boundaries i, j and the index step k are explicitly specified;
  • [i : : k] – the second boundary j is missing;
  • [ : j : k] – the first boundary i is missing;
  • [ : : k] – both boundaries i, j are absent;
  • [ : : ] – both boundaries i and j are absent and the step of index k is absent.

 

5.1. The form [i: j : k]

With this form, all elements of the string are pulled starting from position i, ending with position j-1 inclusively with an offset (step) k. If k<0, then the order of the boundaries i, j is reversed.

Example.

# Extended slice assignment form [i:j:k]
S = '0123456789'

# k>=0
S2 = S[1:8:2] # S2 = '1357'
S3 = S[0:8:3] # S3 = '036'

# k<0
S4 = S[9:0:-2] # S4 = '97531'
S5 = S[9:0:-1] # S5 = '987654321'

 

5.2. The form [i : : k]

In this form, the middle boundary is omitted. If k>= 0, then the string is processed from position i to the end of the string. If k <0, then the string is processed from position i to the beginning of the string in the reverse order.

Example.

# Extended slice assignment form [i::k]
S = 'abcdefghijklmno'

# k>=0
S2 = S[1::2] # S2 = 'bdfhjln'
S3 = S[5::3] # S3 = 'filo'

# k<0
# string in reverse through character
S4 = S[len(S)::-2] # S4 = 'omkigeca'

# string in reverse order
S5 = S[len(S)::-1] # S5 = 'onmlkjihgfedcba'

 

5.3. The form [ : j : k]

With this form, the first boundary i is absent. If the value k>=0, then i is taken equal to the beginning of the string (i=0). If the value k<0, then the string is considered from the end to the beginning, and the value i is taken equal to the end of the string.

Example.

# Extended slice assignment form [:j:k]
S = 'abcdefghijklmno'

# k>=0
S2 = S[:len(S):2] # S2 = 'acegikmo'
S3 = S[:10:3] # S3 = 'adgj'

# k<0
# string in reverse through character
S4 = S[:0:-2] # S4 = 'omkigec'

# string in reverse without the first character
S5 = S[:0:-1] # S5 = 'onmlkjihgfedcb'

# string in reverse order with the first character
S6 = S[:-len(S)-1:-1] # S6 = 'onmlkjihgfedcba'

 

5.4. The form [ : : k]

This form does not contain the extreme boundaries of the string i, j. This means that the values i, j by default indicate the extreme characters of the processed string.

If k>=0, then the string is considered from beginning to end. In this case, i is equal to the index of the first position of the string (i=0), and the value j-1 is equal to the index of the last character of the string.

If k<0, then the line is considered from the end to the beginning. In this case, the value i is taken equal to the index of the last character of the string. The value j is taken equal to the index of the first character of the string.

Example.

# Extended slice assignment form [::k]
S = 'abcdefghijklmno'

# k>=0
S2 = S[::2] # S2 = 'acegikmo'
S3 = S[::3] # S3 = 'adgjm'

# k<0
# string in reverse through character
S4 = S[::-2] # S4 = 'omkigeca'

# string in reverse order
S5 = S[::-1] # S5 = 'onmlkjihgfedcba'

 

5.5. The form [ : : ]

With this form, the original string is copied to another string completely without change.

Example.

# Extended slice assignment form [::]
S = 'abcdefghijklmno'
S2 = S[::] # S2 = 'abcdefghijklmno'

 

6. Operation slice(). Getting the slice object. Examples

Python has a separate slice() operation that allows you to get a slice object. The general form of the operation is as follows:

slice(i, j, k)

where

  • i, j – respectively, the lower and upper boundary of the slice. If there is no border, then the service word None is indicated instead;
  • k – step by index.

Example.

# Getting a slice object
# Operation slice

S = 'abcdefgh'
S2 = S[slice(2, 5)] # S2 = 'cde' - a slice object is created
S3 = '0123456789'[slice(3,8)] # S3 = '34567'

S4 = S[slice(5, None, -1)] # S4 = 'fedcba' - the object of extended slice
S5 = S[slice(None, None, 2)] # S5 = 'aceg'
S6 = 'Hello'[slice(None, None, -1)] # S6 = 'olleH'

 


Related topics