Python String
A Python string is a sequence of characters used to represent text. String literals are written in single or double quotation marks, and both produce the same kind of value; having two forms lets one kind of quotation mark appear inside the other. Triple quotation marks hold text that spans several lines.
A backslash starts an escape sequence, which gives the next character a different meaning: \n is a line break, \t a tab, \" a quotation mark that does not end the string, and \\ a single backslash. To see a value exactly as Python would write it, including escapes and trailing spaces, use repr() rather than print().
Strings are immutable: once created, a string cannot be modified in place. Assigning to a position, as in code[0] = "B", raises TypeError. Methods such as replace(), strip(), lower(), and removeprefix() return a string result without changing the original. Use the returned value, for example by assigning it to a name. An unchanged result may reuse the original object. Immutability is what makes a string safe to share between names and usable as a dictionary key.
Only some operators apply to text. + joins two strings and inserts no separator of its own; * with an integer repeats a string. Subtraction and division raise TypeError, and so does "Total: " + 42, because Python will not mix text with a number. len() counts Unicode code points, not necessarily visible characters: a letter plus a combining accent counts as two. Encoded byte length depends on the encoding.
Reference: Python text sequence type: str. See it in use in Python Strings, Conditions, and Loops.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
