Intro to Python

7. Strings

Strings are data types used to store words or text. They are easily spotted in code because string values normally have quotation marks around them. One of the first lines of code one may write when learning to code is printing the famous “Hello World!”

print("Hello World!");
> Hello World!

Notice how in each print statement the string that was printed, “Hello World!” needed to be surrounded by quotation marks. The quotation marks are how the computer differentiates a string from other lines of code, such as a variable name.

x = 5
print("This is the letter: " + "x")
> This is the letter: x
print("This is the variable: " + str(x))
> This is the variable: 5

Strings are stored differently in different languages. For example, strings in Java are stored as their own objects of the Java Class, while strings in C/C++ are stored as arrays(lists) of characters. This leads to differences in how Strings can be accessed and manipulated. If we wanted to print the first letter of a string, we would have to do it differently in each language.

ourString = "hi"
# prints first letter of string
> h

The letter ‘h’ of “hi” is called a substring of the entire string, and as its name suggests, it is part of the string. In Python, you directly access the array of characters that stores the string. You can use this to access parts of a string, getting substrings of different lengths. If we wanted to gather the substring “you d” from the string “How are you doing”, we would code

question = "How are you doing"
# first parameter is start position (inclusive), second parameter is end position (exclusive)
> you d

Note: In Python, you would use the positions of the first character you want to include and the one index more than the last character you want to include.

Keep in mind that despite their differences, strings are just arrays of characters, so remember that the first letter of a string is stored at a position (index) of 0 like an array in most languages.

Strings are also immutable in many languages, which means that once you create a data of the type string, you cannot change it. Thus, if you want to manipulate strings, you may need to access the original string while using other strings and methods. You can perform many more functions on strings, due to them having many attributes, and a common field used when working with strings is their length.

x = "1234567"
# gets length of string
xLength = len(x)
> 7

You can play around with all the code we've used in this article on Trinket: