Скачать презентацию
Идет загрузка презентации. Пожалуйста, подождите
Презентация была опубликована 11 лет назад пользователемВячеслав Абрамцев
1 Python. Lecture 02
2 Найдите все составные числа меньшие N, которые представимы в виде произведения двух простых чисел.
3 #!/usr/bin/env python def primes(N): l = list(range(2,N)) for x in l: n = x while x*n
4 Python Строки…
5 Unicode & UTF-8 ЭТО РАЗНЫЕ ВЕЩИ!!!
6 Создание строк I am a string I too Do not forget about me! I am a pretty multiline string! str([1, 2]) str({x: 1}) Dont forget about me!
7 Экранированные символы \\ \ \n \t \uxxxx \Uxxxxxxxx
8 Сырые строки rСтрока – не экранируются символы >>> s = "\t" >>> print(s) >>> s '\t' >>> s = r"\t" >>> print(s) \t >>> s '\\t' >> print(s) >>> s '\t' >>> s = r"\t" >>> print(s) \t >>> s '\\t'">
9 Извлечение данных >>> s = "It's interesting lecture!" >>> "lecture" in s True >>> s.index("s") 3 >>> s.find("s") 3 >>> s.index("!!") Traceback (most recent call last): File " ", line 1, in ? ValueError: substring not found >>> s.find("!!") >> "lecture" in s True >>> s.index("s") 3 >>> s.find("s") 3 >>> s.index("!!") Traceback (most recent call last): File " ", line 1, in ? ValueError: substring not found >>> s.find("!!")">
10 «Изменчивость» строк Строки не изменяемы! >>> s = "It's interesting lecture!" >>> s "It's interesting lecture!" >>> s[4] ' >>> s[4]='_' Traceback (most recent call last): File " ", line 1, in ? TypeError: object doesn't support item assignment >> s "It's interesting lecture!" >>> s[4] ' >>> s[4]='_' Traceback (most recent call last): File " ", line 1, in ? TypeError: object doesn't support item assignment">
11 Срезы S = Python S[Start:Finish:Step] S[:] #Python J+S[1:] #Jyton S[:-1] #Pytho S[::-1] #nohtyP
12 Форматирование строк %s % 10 # 10 %s - %s - %s % (10, 20, 30) %(x)s - %(b)s % {x : 19, b : Dad} %10d % 2 # 2
>> s " \n\t It's interesting lecture! \n\t\r" >>> print(s) It's interesting lecture! >>> s.upper(); " \n\t IT'S INTERESTING LECTURE! \n\t\r" >>> s.lower() " \n\t it's interesting lecture! " title="Модификация >>> s = " \n\t It's interesting lecture! \n\t\r" >>> s " \n\t It's interesting lecture! \n\t\r" >>> print(s) It's interesting lecture! >>> s.upper(); " \n\t IT'S INTERESTING LECTURE! \n\t\r" >>> s.lower() " \n\t it's interesting lecture! " class="link_thumb"> 13 Модификация >>> s = " \n\t It's interesting lecture! \n\t\r" >>> s " \n\t It's interesting lecture! \n\t\r" >>> print(s) It's interesting lecture! >>> s.upper(); " \n\t IT'S INTERESTING LECTURE! \n\t\r" >>> s.lower() " \n\t it's interesting lecture! \n\t\r" >>> s.lstrip() "It's interesting lecture! \n\t\r" >>> s.rstrip() " \n\t It's interesting lecture!" >>> s.strip() "It's interesting lecture!" >> s " \n\t It's interesting lecture! \n\t\r" >>> print(s) It's interesting lecture! >>> s.upper(); " \n\t IT'S INTERESTING LECTURE! \n\t\r" >>> s.lower() " \n\t it's interesting lecture! "> >> s " \n\t It's interesting lecture! \n\t\r" >>> print(s) It's interesting lecture! >>> s.upper(); " \n\t IT'S INTERESTING LECTURE! \n\t\r" >>> s.lower() " \n\t it's interesting lecture! \n\t\r" >>> s.lstrip() "It's interesting lecture! \n\t\r" >>> s.rstrip() " \n\t It's interesting lecture!" >>> s.strip() "It's interesting lecture!""> >> s " \n\t It's interesting lecture! \n\t\r" >>> print(s) It's interesting lecture! >>> s.upper(); " \n\t IT'S INTERESTING LECTURE! \n\t\r" >>> s.lower() " \n\t it's interesting lecture! " title="Модификация >>> s = " \n\t It's interesting lecture! \n\t\r" >>> s " \n\t It's interesting lecture! \n\t\r" >>> print(s) It's interesting lecture! >>> s.upper(); " \n\t IT'S INTERESTING LECTURE! \n\t\r" >>> s.lower() " \n\t it's interesting lecture! ">
14 Модификация Команды strip, lstrip, rstrip, upper, lower возвращают НОВУЮ строку. НО! >>> s = s.strip() >>> s "It's interesting lecture!"
15 Модификация >>> xmltags = " " >>> xmltags.strip(""); 'a> ' >>> xmltags.strip(" "); ' ' >> xmltags.strip(""); 'a> 111 222111 222' >>> xmltags.strip(" "); '111 222'">
16 Извлечение данных >>> s = "a,b,cccc,d" >>> s.split(","); ['a', 'b', 'cccc', 'd'] >>> s.split(", "); ['a,b,cccc,d'] >>> s.split(",", 2); ['a', 'b', 'cccc,d'] >> s.split(","); ['a', 'b', 'cccc', 'd'] >>> s.split(", "); ['a,b,cccc,d'] >>> s.split(",", 2); ['a', 'b', 'cccc,d']">
17 Join >>> some_list = ['one', 'two', 'three'] >>> ', '.join(some_list) 'one, two, three' >>> ''.join(some_list) 'onetwothree' >>> some_list2 = [1, 2, 3] >>> ', '.join(some_list2) Traceback (most recent call last): File " ", line 1, in ? TypeError: sequence item 0: expected string, int found >>> ', '.join([str(i) for i in some_list2]) '1, 2, 3' >> ', '.join([str(i) for i in some_list2]) '1, 2, 3'">
18 Проверка типа содержимого S.isdigit() S.isalpha() …. S.istitle()
19 Unicode (Python 2) >>> u"Привет" u'\xf0\xd2\xc9\xd7\xc5\xd4' >>> unicode("Привет", "koi8-r") u'\u041f\u0440\u0438\u0432\u0435\u0442' >>> s = unicode("Привет", "koi8-r") >>> print s.encode("utf-8") п÷яп п п я >>> print s.encode("koi8-r") Привет >> unicode("Привет", "koi8-r") u'\u041f\u0440\u0438\u0432\u0435\u0442' >>> s = unicode("Привет", "koi8-r") >>> print s.encode("utf-8") п÷яп п п я >>> print s.encode("koi8-r") Привет">
20 Regexp >>> import re >>> regexp = "{{(.*?)}}" >>> str = "{{this}} is {{strange}} string" >>> for match in re.findall(regexp, str):... print "FIND: ", match... FIND: this FIND: strange >> str = "{{this}} is {{strange}} string" >>> for match in re.findall(regexp, str):... print "FIND: ", match... FIND: this FIND: strange">
21 Regexp - compiled >>> import re >>> regexp = re.compile("{{(.*?)}}") >>> str = "{{this}} is {{strange}} string" >>> for match in regexp.findall(str):... print "FIND: ", match... FIND: this FIND: strange >> str = "{{this}} is {{strange}} string" >>> for match in regexp.findall(str):... print "FIND: ", match... FIND: this FIND: strange">
22 Regexp finditer match search
>> file_in = open("foo.txt", "r") >>> str = file_in.read() >>> print str Hello i a" title="Чтение из файла >>> file_in = open("test.txt", "r") Traceback (most recent call last): File " ", line 1, in ? IOError: [Errno 2] No such file or directory: 'test.txt' >>> file_in = open("foo.txt", "r") >>> str = file_in.read() >>> print str Hello i a" class="link_thumb"> 23 Чтение из файла >>> file_in = open("test.txt", "r") Traceback (most recent call last): File " ", line 1, in ? IOError: [Errno 2] No such file or directory: 'test.txt' >>> file_in = open("foo.txt", "r") >>> str = file_in.read() >>> print str Hello i am pretty file! >>> str.split() ['Hello', 'i', 'am', 'pretty', 'file!'] >>> str.splitlines() ['Hello', 'i am', 'pretty ', 'file!'] >> file_in = open("foo.txt", "r") >>> str = file_in.read() >>> print str Hello i a"> >> file_in = open("foo.txt", "r") >>> str = file_in.read() >>> print str Hello i am pretty file! >>> str.split() ['Hello', 'i', 'am', 'pretty', 'file!'] >>> str.splitlines() ['Hello', 'i am', 'pretty ', 'file!']"> >> file_in = open("foo.txt", "r") >>> str = file_in.read() >>> print str Hello i a" title="Чтение из файла >>> file_in = open("test.txt", "r") Traceback (most recent call last): File " ", line 1, in ? IOError: [Errno 2] No such file or directory: 'test.txt' >>> file_in = open("foo.txt", "r") >>> str = file_in.read() >>> print str Hello i a">
24 Запись в файл >>> file_out = open("test.txt", "w") >>> file_out.write("Test file\nNew line"); >>> file_out.close() >>> try:... f = open("file.txt", "w")... f.write("test")... finally:... f.close() >> file_out.write("Test file\nNew line"); >>> file_out.close() >>> try:... f = open("file.txt", "w")... f.write("test")... finally:... f.close()">
25 Работа с файлами файла - 2 read(size) readline(size) readlines(size) writelines
26 Стандартный ввод и вывод #!/usr/bin/env python import sys counter = 1 while True: line = sys.stdin.readline() if not line: break print %s: %s % (counter, line) counter += 1
27 Стандартный ввод import sys for I, line in enumerate(sys.stdin): print %s: %s % (I, line) sys.stdout.write(OK!)
28 StringIO >>> from StringIO import StringIO >>> str = StringIO("aaaa"); >>> str.read() 'aaaa' >>> str.write("bbbb") >>> str >>> print str >>> str.getvalue() 'aaaabbbb' >> str.read() 'aaaa' >>> str.write("bbbb") >>> str >>> print str >>> str.getvalue() 'aaaabbbb'">
29 Urllib >>> import urllib >>> url_file = urllib.urlopen(" >>> url_file.read(100) ' >> url_file.read(100) '">
30 ДЗ 1.Вывести греческий алфавит 2.Реализовать длинную арифметику (ЧЕСТНО!) 3.Используя модуль ElementTree, вывести в древовидном виде RSS ленту 4.Подсчитать на странице с результатами поиска Google статистику по доменам первого уровня
Еще похожие презентации в нашем архиве:
© 2024 MyShared Inc.
All rights reserved.