1.4 String basics
Learning objectives
By the end of this section you should be able to
- Use the built-in
lenfunction to get a string's length. - Concatenate string literals and variables using the + operator.
Quote marks
A string is a sequence of characters enclosed by matching single (') or double (") quotes. Ex: "Happy birthday!" and '21' are both strings.
To include a single quote (') in a string, enclose the string with matching double quotes ("). Ex: "Won't this work?" To include a double quote ("), enclose the string with matching single quotes ('). Ex: 'They said "Try it!", so I did'.
| Valid string | Invalid string |
|---|---|
"17" or '17' | 17 |
"seventeen" or 'seventeen' | seventeen |
"Where?" or 'Where?' | "Where?' |
"I hope you aren't sad." | 'I hope you aren't sad.' |
'The teacher said "Correct!" ' | "The teacher said "Correct!" " |
len function
A common operation on a string object is to get the string length, or the number of characters in the string. The len function, when called on a string value, returns the string length.
Concatenation
Concatenation is an operation that combines two or more strings sequentially with the concatenation operator (+). Ex: "A" + "part" produces the string "Apart".