Store Text with Strings in Python
To store text in Python, you need to surround it with quotation marks. For instance, you can store the word "Python"
in the language
variable and then display it:
12345# Save string within variable language = 'Python' # Output string print(language)
Variables that store text are known as strings. A string is a sequence of characters used to represent text in Python. Strings are enclosed in either single quotes ('
) or double quotes ("
).
Although strings can contain numbers, they are treated as text, meaning you cannot perform mathematical operations on them directly. To use a number stored as a string in calculations, you need to convert it to a numeric type first.
123hour = '16' print(hour)
You can use either single quotes (' '
) or double quotes (" "
) to define a string in Python—both work the same way. However, if you need to include one type of quote inside the string, you have a few options.
123456789# Using double quotes outside message = "It's a beautiful day!" # Using single quotes outside greeting = 'He said, "Hello!"' # Use \ to escape single quote inside single-quoted string message = 'It\'s a beautiful day!' # Use \ to escape double quote inside double-quoted string greeting = "He said, \"Hello!\""
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Spørg mig spørgsmål om dette emne
Opsummér dette kapitel
Vis virkelige eksempler
Awesome!
Completion rate improved to 1.64
Store Text with Strings in Python
Stryg for at vise menuen
To store text in Python, you need to surround it with quotation marks. For instance, you can store the word "Python"
in the language
variable and then display it:
12345# Save string within variable language = 'Python' # Output string print(language)
Variables that store text are known as strings. A string is a sequence of characters used to represent text in Python. Strings are enclosed in either single quotes ('
) or double quotes ("
).
Although strings can contain numbers, they are treated as text, meaning you cannot perform mathematical operations on them directly. To use a number stored as a string in calculations, you need to convert it to a numeric type first.
123hour = '16' print(hour)
You can use either single quotes (' '
) or double quotes (" "
) to define a string in Python—both work the same way. However, if you need to include one type of quote inside the string, you have a few options.
123456789# Using double quotes outside message = "It's a beautiful day!" # Using single quotes outside greeting = 'He said, "Hello!"' # Use \ to escape single quote inside single-quoted string message = 'It\'s a beautiful day!' # Use \ to escape double quote inside double-quoted string greeting = "He said, \"Hello!\""
Tak for dine kommentarer!