Python Language String: Difference between revisions
Line 11: | Line 11: | ||
s1 = 'abc' | s1 = 'abc' | ||
s2 = "xyz" | s2 = "xyz" | ||
</syntaxhighlight> | |||
Declaring string literals bounded by single and double quotes is equivalent. There are two types of quotes to make it possible to create strings that include single and double quotes: a single-quoted string allows specifying double quotes inside and a double-quoted string allows specifying single quotes inside: | |||
<syntaxhighlight lang='py'> | |||
s1 = 'the color is "red"' | |||
s2 = "the shape is 'square'" | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 19:17, 18 June 2022
Internal
Overview
String are a Python sequence of characters. Strings are immutable, a string cannot be changed in-place. Python 3 supports the Unicode standard, so Python 3 strings can contain characters from any written language in the world.
Quotes
String literals can be declared using four type of quotes: sigle quotes '...'
, double quotes "..."
, triple single quotes '''...'''
and triple double quotes """..."""
.
Single and Double Quotes
s1 = 'abc'
s2 = "xyz"
Declaring string literals bounded by single and double quotes is equivalent. There are two types of quotes to make it possible to create strings that include single and double quotes: a single-quoted string allows specifying double quotes inside and a double-quoted string allows specifying single quotes inside:
s1 = 'the color is "red"'
s2 = "the shape is 'square'"
The [] Operator and String Slices
The []
operator can be used to read strings from the sequence, but not modify the sequence. Because strings are immutable, an attempt to change a character at a specific position in string will throw an TypeError
exception:
s = 'abc'
s[0] = 'x'
[...]
TypeError: 'str' object does not support item assignment