Python strings
In Python a string of characters can be enclosed in either single quotes or double quotes:
'Yes we can' "Yes we can"
You can choose. This can come in handy if you want to put one kind of quote in a string.
'"Yes we can," said the president' "'Yes we can,' said the president"
If you want to put both kinds of quotes in a string, you have to escape one of them. To do that use the backslash (\) character
"'No we can\'t,' said the president" '"No we can\'t," said the president'
If we use the backslash to escape, then how do we put a backslash in a string? We double it
'\\'
Try this. It returns a string with a single backslash.
Another escape is a newline. We can put a newline in a string like this
'oneline\nanother line'
This string prints like this:
print('one line\nanother line') one line another line
We can join strings together by 'adding' them
'one string' + 'two string' 'one stringtwo string'
The
+operator is polymorphic.In fact, you don't even need the
+operator if you're joining two literal strings'one string' 'two string' 'one stringtwo string'
However this doesn't work for joining identifiers whose values are strings.
We can write a long string that spans several lines and includes line breaks by placing it between triple quotes. The resulting string includes the line breaks. Here is some lorem ipsum:
long_string = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""
We can ask a string what names are associated with it using
dirdir('abc') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
That's quite a lot! Ignoring the ones with underscores in their names for the time being, let's ask one of these what it does.
help('abc'.strip) Help on built-in function strip: strip(...) method of builtins.str instance S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
Let's try it out:
' surrounded by spaces '.strip() 'surrounded by spaces'
- Try out some of the other string functions yourself.
- Sometimes you want to build a string that contains representations of some values. Python has some powerful string formatting tools for this. (We use the so called new style formatting.)
Note that Python represents a Unicode character as a string of length one
'abcd'[0] 'a'
Unicode characters can be entered by number or name
'\u0394' 'Δ' '\N{SKULL AND CROSSBONES}' '☠' '\u2603' '☃' '\N{snowman}' '☃'
See the Unicode HOWTO for more information.