3.5. String Define¶
str
is a sequence of characters
3.5.1. Syntax¶
Empty string:
>>> data = ''
Define string:
>>> data = 'Mark Watney'
Multiline string:
>>> data = 'First line\nSecond line\nThird line'
>>> data = """First line
... Second line
... Third line"""
3.5.2. Quotes or Apostrophes¶
"
and'
works the sameChoose one and keep consistency in code
Python console prefers single quote (
'
) characterIt matters for
doctest
, which compares two outputs character by characterPEP 257 -- Docstring Conventions: For multiline
str
always use three double quote ("""
) characters
Both "
and '
works the same
>>> a = 'It is Monty Python'
>>> b = "It is Monty Python"
>>>
>>> a == b
True
Python console prefers single quote ('
) character:
>>> text = 'It is Monty Python'
>>> text
'It is Monty Python'
>>>
>>> text = "It is Monty Python"
>>> text
'It is Monty Python'
Why we have both?
>>> text = 'It\'s Monty Python'
>>> text
"It's Monty Python"
>>>
>>> text = "It's Monty Python"
>>> text
"It's Monty Python"
It's better to use double quotes, when text has apostrophes. This is also a default the behavior of Python console, which prefers less escape characters:
>>> text = 'It\'s Monty Python'
>>> text
"It's Monty Python"
However HTML and XML uses double quotes to enclose attribute values, hence it's better to use single quotes for the string:
>>> html = '<a href="https://python.astrotech.io">Python Book</a>'
>>> html
'<a href="https://python.astrotech.io">Python Book</a>'
>>>
>>> html = "<a href=\"https://python.astrotech.io\">Python Book</a>"
>>> html
'<a href="https://python.astrotech.io">Python Book</a>'
Errors:
>>> text = 'It's Monty Python'
Traceback (most recent call last):
SyntaxError: unterminated string literal (detected at line 1)
>>> html = "<a href="https://python.astrotech.io">Python Book</a>"
Traceback (most recent call last):
SyntaxError: invalid syntax
PEP 257 -- Docstring Conventions: For multiline str
always use three
double quote ("""
) characters
>>> text = """It's \"Monty Python\""""
>>> text = '''It\'s "Monty Python"'''
3.5.3. Docstring¶
PEP 257 -- Docstring Conventions: For multiline
str
always use three double quote ("""
) charactersMore information in Function Doctest
If assigned to variable, it serves as multiline str
otherwise
it's a docstring:
>>> """We choose to go to the Moon!
... We choose to go to the Moon in this decade and do the other things,
... not because they are easy, but because they are hard;
... because that goal will serve to organize and measure the best of our
... energies and skills, because that challenge is one that we are willing
... to accept, one we are unwilling to postpone, and one we intend to win,
... and the others, too."""
>>> text = """We choose to go to the Moon!
... We choose to go to the Moon in this decade and do the other things,
... not because they are easy, but because they are hard;
... because that goal will serve to organize and measure the best of our
... energies and skills, because that challenge is one that we are willing
... to accept, one we are unwilling to postpone, and one we intend to win,
... and the others, too."""
3.5.4. Type Casting¶
Builtin function str()
converts argument to str
>>> str('Moon')
'Moon'
>>>
>>> str(1969)
'1969'
>>>
>>> str(1.337)
'1.337'
Builtin function print()
before printing on the screen
runs str()
on its arguments:
>>> print(1969)
1969
3.5.5. Assignments¶
"""
* Assignment: String Define HelloWorld
* Required: yes
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min
English:
1. Define `result` with value `Hello World`
2. Run doctests - all must succeed
Polish:
1. Zdefiniuj `result` z wartością `Hello World`
2. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> result
'Hello World'
"""
# Expected result: 'Hello World'
# type: str
result = ...
"""
* Assignment: String Define Quotes
* Required: no
* Complexity: easy
* Lines of code: 1 lines
* Time: 5 min
English:
1. To print use f-string formatting
2. Note, that second line starts with tab
3. Value `NAME` in double quotes is a name read from user
4. Mind the different quotes, apostrophes, tabs and newlines
5. Do not use neither space not enter - use `\n` and `\t`
6. Do not use string addition (`str + str`)
7. Run doctests - all must succeed
Polish:
1. Do wypisania użyj f-string formatting
2. Zauważ, że druga linijka zaczyna się od tabulacji
3. Wartość `NAME` w podwójnych cudzysłowach to ciąg od użytkownika
4. Zwróć uwagę na znaki apostrofów, cudzysłowów, tabulacji i nowych linii
5. Nie używaj spacji ani klawisza enter - użyj `\n` i `\t`
6. Nie korzystaj z dodawania stringów (`str + str`)
7. Uruchom doctesty - wszystkie muszą się powieść
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> print(result) # doctest: +NORMALIZE_WHITESPACE
'''My name... "José Jiménez".
I'm an \"\"\"astronaut!\"\"\"'''
"""
NAME = 'José Jiménez'
# Add whitespace and quotes to: My name... José Jiménez. I'm an astronaut!
# type: str
result = ...