Skip to content

String Operations

String Operations

Strings are sequences of letters, numbers, symbols, and spaces. In Python, strings can be almost any length. String variables are assigned in Python using quotation marks ' '. Strings can contain blank spaces. A blank space is a valid string character in Python string.

>>> string = 'z'
>>>> type(string)
<class 'str'>

>>> string = 'Engineers'
>>> type(string)
<class 'str'>

Strings are sequences of letters, numbers, spaces, and punctuation. Operations that can be accomplished with strings include indexing, concatenation, and logical comparisons.

Indexing

Individual characters or groups of characters can be accessed from within a string using indexing. Indexing is the process of specifying a location within a string. Other words used for index include position and location. If we index the first location within a string, we are returned whatever character is stored at the first position. Indexing strings entails using square brackets [ ] immediately after the string. A number or range of numbers is specified within the square brackets.

>>> word = 'Solution'
>>> word[0]
'S'
>>> word[2]
'1'
>>> word[-1]
'n'

The colon operator : can be used when indexing strings and lists. In the statement:

>>> word[0:3]
'Sol'

the colon operator means "thru". In this case 0 thru 3. Remember that Python counting starts at zero and ends at n+1. 0:3 returns the first three characters in the string. With no numbers, the colon operator means "all"

>>> word[:]
'Solution'

With three numbers the colon operator denotes start:stop+1:step

>>> word[0:8:2]  #start:stop+1:step
'Slto'

Negative steps indicate returning the characters in the string backwards.

>>> word[::-1] # start=not specified :stop=not specified:step=-1
'noituloS'

Concatenation

The word concatenate means to combine. When Python strings are concatenated, two or more strings are combined into one long string. In Python, strings can be concatenated with the addition operator, the plus sign +.

>>> first ='Kendra '
>>> last = 'Wong'
>>> full = first + last
>>> full
'Kendra Wong'

Multipying a string by a number, repeats the string that number of times.

>>> alarm = 'Help! '
>>> alarm*5
'Help! Help! Help! Help! Help! '