Strings
A string is a sequence of characters. A character could be an English letter, a digit, or a symbol. Emojis, characters of languages other than the English language are all characters. The collection of all possible characters is in the ASCII standard. In Python we can construct a string literal, that is, a value of type string. Thus, we can also store strings in variables similar to the numeric types. However, strings are different than numeric types. First, strings consist of a collection of characters. Numeric values can be constructed only from digits and the decimal point. Operations of strings are also different. Some operators that work for numeric types also work for strings but have different meanings.
To define a string literal, we should use a single or a double quotation mark:
s = 'This is a string'
t = "This is also a string"
Note that a string starts with a quotation mark and ends with it. Each character in a string has an index and indexes start with 0 and end with the N-1, where N is the number of characters in the string.
String Indexing
Strings are values and could be stored in any variable. One can work with parts of a string by using indexing: the string "Kuwait"
has the following indexes: 0, 1, 2, 3, 4, 5 and -1, -2, -3, -4, -5, -6. For example, "Kuwait"[-1]
evaluates to the string "t"
. One can get more than one character of a string by defining a range: "Kuwait"[:2]
which evaluates to "Ku"
.
-6 | -5 | -4 | -3 | -2 | -1 |
K | u | w | a | i | t |
0 | 1 | 2 | 3 | 4 | 5 |
String Functions and Methods
We can apply functions and methods to strings. For example, we can check how many characters are in a string and print it for the user:
x = input("Enter your name: ")
print("Your name has", len(x), "characters.")
This program receives a string and stores it in x. Then, len(x)
produces an integer value N equal to the number of characters in x
. The print function displays this value on the screen.
What if we want to know if a string exists in another string? We can use a string method, which is a function that applies to a value of type string. To find if a string is part of another string, we can use the find
method, which returns the index of s
if s
is in t
or -1 otherwise:
'hello world'.find('l') #returns 2
'hello world'.find('x') #returns -1
The find
method searches for s
in t
from left to right and returns the first index of s
in t
.
We can reverse this by using the rfind
method, which searches for s
in t
but from the right to the left:
'hello world'.rfind('l') #returns 9
'hello world'.rfind('o') #returns 7
Note that find
and rfind
only use nonnegative indexes except when s
is not found.
We can also count the occurrences of a string s
in another string t
using the count
method:
x = t.count(s)
In this program, x
is an integer equal to the number of times s
appeared in t
.
Other useful string functions, assuming s
is a string:
s.upper()
s.lower()
s.captialize()
s.title()
Strings can be sliced. That is, we can extract a part of a string (a slice) and store it in a variable or print it on the screen.
String slicing works with string indexes. We can specify a range of indexes to represent a new slice of a string to be extracted. For example, if we want to slice the first half of a string s
, we can do the following:
n = len(s) //2
t = s[0:n]
In general, a slice s[x:y]
is all the characters in s
starting with index x
until before (excluding) the index y
.
Example:
s = 'hello world'
t = s[0:5]
print(t) #This will print 'hello'
We can use default slicing values. If we are starting with index 0, we can just omit 0. For example, s[0:5]
becomes s[:5]
. If we want to go from index x
to the last index in the string, we can write s[x:]
. We can also use negative indexes for slicing with the same effect.
We can use a trick to reverse the characters of a string:
s = 'hello'
print(s[::-1]) #This will print 'olleh'
Other types can be converted to strings. For example, we may need to convert a number from a numeric type to a string type. The following program tries to print the first digit of an integer x
by converting it to a string. Note that to convert a numeric value to a string, we can use the built-in str
function.
x = 100
s = str(x)
print(s[0])
Python Strings and Input
To receive input from the user, programmers can use the input()
function, for example, s = input()
, which will cause the program to wait for something to be provided by the user using the keyboard. As soon as the user hits on enter, the program collects all the characters that the user entered on the keyboard and stores them as a string in the variable s
(or whatever variable you want to have).
Converting input to useful types
When receiving an input x = input()
, the value stored in x
is always a string. If the user enters a number on the keyboard, the number will also be stored as a string. For example, say the user wants to run the following program:
x = input()
y = input()
z = x + y
When prompted for x
and y
, the user enters 10
and 20
. What would be the result in z
? We expect the result to be 30
but the result will be 1020
. This is because +
on a string does NOT add the two strings together but concatenates the two strings; that is, it puts them together in a single string. If we want to add two numbers that we received from the user on the keyboard, we need to convert the two strings containing user numbers to numeric types:
x = input()
y = input()
x = float(x) #or int(x)
y = float(y) #or int(y)
z = x + y
When running this program, if the user enters 10
and 20
for x
and y
, the result in z
will be 30
. This is because the function int
, when applied to a string containing only numbers, generates a value of type integer. Similarly, float
generates a value of type float
.