Mark As Completed Discussion

In this lesson, we will discuss one of the basic types in programming languages, with a focus on the following key points,

  1. What are strings, and common string operations?
  2. Working with strings in one of a few introductory programming languages.

This is a general purpose tutorial for multiple languages. For the Javascript-specific version of this lesson that focuses on fundamentals frontend engineers need to know, please click here.

In the previous lessons, we learnt about variables and their usage. In programming languages, these variables can be assigned values of different types. These include integers, decimal numbers, sequence of alphabetical letters, booleans (true or false) among several others. Programming languages not only offer these data types, but also allow programmers to perform various operations on them. In this lesson, we will focus on the data type called string, and the operations that are defined on strings.

Strings: A Wonderful Sequence of Characters

Strings are one of the most fundamental and commonly used data types in programming. A string represents a sequence of characters and can be as simple as a single letter or as complex as an entire book.

Definition and Declaration

  • What is a String?: A string consists of a sequence of characters, such as numbers, letters, spaces, or special symbols. Think of it as a chain of characters linked together.
  • Quotation Marks: Strings are usually enclosed within single ('') or double quotation marks (""). This tells the compiler or interpreter that the text inside the quotes should be treated as a single unit.
  • Unicode Characters: Strings are made up of Unicode characters, allowing them to represent virtually any character in any writing system.

Strings as Arrays of Characters

  • Accessing Characters: Since strings are essentially arrays of characters, individual characters can be accessed and manipulated in many programming languages.
  • Indexing: Characters within a string can be accessed by their position (or index) in the sequence, typically starting from 0.

Manipulating Strings

  • Concatenation: Strings can be combined or concatenated to form new strings.
  • Methods and Functions: Most languages provide various built-in methods and functions to work with strings, such as finding the length, transforming case, replacing characters, etc.

Strings in Different Programming Languages

Now, let's look at how strings are used and manipulated in various programming languages:

1import "fmt"
2greeting := "Hello World!"
3length := len(greeting) // Getting the length
4firstChar := greeting[0] // Accessing the first character (in byte)

Strings in Code

As mentioned above, strings in most programming languages can be declared by single or double quotation marks, and so is the case with Python. Following code block shows some examples of string declaration in Python.

1var name string = "Chris"
2var email string = "chris123@gmail.com"
3var book string = "The Great Gatsby"
4var author string = "F. Scott Fitzgerald"

In Python, characters in a string can be accessed by providing an index, which is the position of the character that need to be accessed inside a pair of square brackets ([]). Suppose we wanted to access the character r in the name string above. The position of r in the string is 2. This is because the indices, or the positions in a string start from 0, and not 1, as illustrated below.

Strings in Code

The subsequent code will be:

1name := "Chris"
2fmt.Println(string(name[2])) // prints 'r'

Python also has some specified string methods which allow to manipulate strings more easily. These will be discussed in the string operations section below.

Are you sure you're getting this? Is this statement true or false?

Does the following code block declare a valid string in Python?

1var country = "India"

Press true if you believe the statement is correct, or false otherwise.

Let's test your knowledge. Is this statement true or false?

Strings cannot have capital letters.

Press true if you believe the statement is correct, or false otherwise.

Operations on Strings

In programming languages, operations are defined on different data types, including strings. These operations could be regarding comparison of strings, combination, removal, or addition of characters/strings. Let's work with them in detail in the following sections.

String Operations in Python

First string operation to discuss is concatenation. This operation allows us to combine multiple strings together.

1firstname := "John"
2secondname := "Weather"
3fullname := firstname + " " + secondname
4
5fmt.Println(fullname) //prints "John Weather"
6
7book := "The Great Gatsby"
8author := "F. Scott Fitzgerald"
9
10sentence := book + " was written by " + author
11
12fmt.Println(sentence) //prints "The Great Gatsby was written by F. Scott Fitzgerald"

Multiplication operator *, allows to create a string which repeats itself multiple times. For example,

PYTHON
1name = "Chris"
2
3print(name*3) #prints "ChrisChrisChris"

Other string operations in Python are all implemented through string methods. Let's see some of the examples below.

  • len() method tells us the length of string.
  • count() method tells about the number of times a specified value occurs in string.
  • upper() method converts all the characters in the string to uppercase.

Example usage of these operations can be found in the code block below.

1package main
2
3import (
4	"fmt"
5	"strings"
6)
7
8func main() {
9	book := "The Great Gatsby"
10	author := "F. Scott Fitzgerald"
11
12	fmt.Println(len(book)) // prints 16
13	fmt.Println(strings.Index(author, "z")) // prints 12
14	fmt.Println(strings.Index(author, "Scott")) // prints 3
15	fmt.Println(strings.ToLower(author)) // prints "f. scott fitzgerald"
16}

A comprehensive list of string methods is provided here.

Build your intuition. Click the correct answer from the options.

The output to the following code block in Python will be,

1package main
2import "fmt"
3func main() {
4    name := "Sara"
5    age := "12"
6    fmt.Println(name + age)
7}

Click the option that best answers the question.

  • Sara12
  • Sara 12
  • sara 12

Are you sure you're getting this? Fill in the missing part by typing it in.

The output to the following code in JavaScript will be ___.

1package main
2
3import (
4	"fmt"
5	"strings"
6)
7func main() {
8	text := "Giraffes like to eat leaves."
9	fmt.Println(strings.Count(text, " "))
10}

Write the missing line below.

While working with strings, there are some important properties that need to be taken care of,

  • Strings are immutable. This means that they cannot be reassigned characters. For example, in the example below, we will get an error of item assignment as reassignment of characters is not allowed.
1name := "Lee"
2name = "T" + name[1:]
3fmt.Println(name) // "Tee"
  • To include single quotation inside a string, we need to use double quotation marks to declare them. We cannot use single quotation marks to declare the string if we want to use single quotation marks inside the string.

Summary

In this lesson, we discussed about strings and various string operations that can be performed on them. String operations, as we've seen, are helpful in modifying strings at any time during the program rather than creating the entire string again and again. It also tells us about important properties of the already declared string variables.

One Pager Cheat Sheet

  • In this lesson, we will explore the string type and common related operations in introductory programming languages.
  • Strings are a data type in most programming languages which are declared by enclosing characters with single ('') or double quotation marks ("") and contain a sequence of characters or array of characters which can be accessed and manipulated with properties and methods.
  • Python and JavaScript strings can be declared with single or double quotations, and their characters can be accessed with indices starting from 0, as illustrated by name[2] printing r.
  • Yes, both Python and JavaScript support declaring a string literalusing single or double-quotation marks, as evidenced by the code blocks above.
  • Strings in programming languages such as Python and JavaScript are collections of characters, including both upper and lower case letters, numbers, symbols, and other characters, and are therefore not case-sensitive.
  • Strings can be manipulated through comparison, combination, removal, and addition of characters or strings in programming languages.
  • Python and JavaScript support string concatenation, multiplication, and multiple built-in methods to manipulate strings.
  • The + operator in Python is used to concatenate strings, such as "Sara" and "12" stored in variables name and age, respectively, resulting in the output string "Sara12".
  • The print() function in JavaScript prints the number of spaces in the argument text, which in this example is 4.
  • Strings are immutable and cannot be reassigned characters, so double quotation marks must be used when including single quotation marks in a string.
  • We discussed various string operations that can be used to modify and understand the properties of already declared string variables.