Если видео недоступно для просмотра, попробуйте выключить блокировщик рекламы.

Strings in Python

Common info about strings

  • string is the most suitable data type for human
  • strings are immutable
  • strings are iterable
  • strings are case-sensitive
  • there are two types of strings in Py2.x
  • strings are the main difference b/w Py2 and Py3

How do declare a string

  • Use both single or double quotes
  • Use triple single or double quotes for multiline strings
  • You may combine both types of quotes
'test' == 'Test'  # False

s1 = 'This is a string'
s2 = "And this is too"
s3 = '{"this": ["is", "JSON", "string"]}'
s4 = "You don't fool me"

s5 = '''This is
a multi line
string!'''

query = """    
    SELECT
        id, name, age    
    FROM
        users
    WHERE
        id > 10
        AND name LIKE '%ivan%'
    LIMIT
        42
"""

Docstrings

  • For modules, functions, classes
  • The first line is a short description
  • The blank line separates long description
  • The description
  • Stores in obj.doc attribute
  • help(obj) to show a docstring
# module.py
"""Module to operate on users.

This module is a parts of SuperProject.
Author: Ivan Grishaev <[email protected]>
License: MIT...
"""

def get_user(user_id):
    pass


def get_user(user_id, verbose=False):
    """ Gets user from the database.

    user_id: int, database pk for table `users`,
    verbose: bool, write SQL query to stdout if True
    returns: models.User instance
    """
    pass

class User(models.Model):
    """ Represents user in a database.

    Any information about the class goes there.
    Methods, features, etc.
    """
    pass

Symbols quoting

  • Use \t, \n, \r, \x, \u for special symbols
  • Use \ to quote the following symbol
s1 = 'You don't fool me'   # SyntaxError
s2 = 'You don\'t fool me'  # ok
s3 = 'Do you want to delete c:\\text.txt?'
print '\x55\x32\xee'
>>> U2�

Common string methods

  • .lower(), .upper(), .capitalize() to change case
  • str.split(sep) to split str to a list
  • sep.join(iter) to merge an iterable into a str
  • .replace() to replace text
  • .strip() to remove empty symbols at start and end
'Foo Bar BAZ'.lower()                       'foo bar baz'
'test'.upper()                              'TEST'
'42;John;New-York;USA'.split(';')           ['42', 'John', 'New-York', 'USA']
gen = (x for x in ['part1', 'part2', 'part3'])
'-'.join(gen)                               'part1-part2-part3'
'foo bar baz foo'.replace('foo', 'FOO')     'FOO bar baz FOO'
'  test  '.strip()                          'test'

Raw strings

  • r'...' stands for quoted (raw) string
  • shows symbols as-is
  • useful for regexps
print r'special symbols are \n, \t'
>>> special symbols are \n, \t
print r'\x55\x32\xee'
>>> \x55\x32\xee

How to turn an object to a string

  • use built in str class
  • you can override default str behaviour
str(42)              '42'
str([1, 2, 3])       '[1, 2, 3]'
str(obj)     -->     obj.__str__()

class User(object):
    def __str__(self):
        return 'string for user %s' % self.id

user = User()
str(user)
>>> 'string for user 12345'

Operation on strings

  • Use + operator to concatenate strings
  • Use * operator to repeat a string
what = 'human'
'I ' + 'am ' + 'a ' + what
>>> 'I am a human'
'work, ' * 10
>>> 'work, work, work, work, work, work, work, work, work, work, '

String is iterable

iter('test')     <iterator at 0x10d20ce90>
set('foo')       {'f', 'o'}
list('foo')      ['f', 'o', 'o']

def foo(*args):
    return args

foo(*'foobarbaz')
>>> ('f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'z')

Index access and slices

  • Syntax is close to lists
  • Use [N] clause to get Nth symbol
  • You can only read it
  • Use [start:end;Nth] syntax to slice a string
text = 'Python Language'
text[5]      'n'
text[0]      'P'
text[-1]     'e'
text[::-1]   'egaugnaL nohtyP'
text[::2]    'Pto agae'
text[7:]     'Language'

text[2] = 'A'# TypeError: 'str' object does not support item assignment

In operator

langs = 'php java python c# brainfuck turtle'
'java' in langs                      True
'c#' in langs                        True
'Python' in langs                    False
'Python'.upper() in langs.upper()    True

response = '{"status": "error", "description": "no enough money"}'
ok = 'error' not in response
if not ok:
    handle_error()

Next lesson

  • unicode strings
  • encoding/decoding strings
Мы учим программированию с нуля до стажировки и работы. Попробуйте наш бесплатный курс «Введение в программирование» или полные программы обучения по Node, PHP, Python и Java.

Хекслет

Подробнее о том, почему наше обучение работает →