Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

1.4 String basics

Learning objectives

By the end of this section you should be able to

  • Use the built-in len function 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'.

Table 1.3 Rules for strings.
Valid stringInvalid 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".

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.