{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Web-scraping: сбор данных из баз данных и интернет-источников\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*\n", "\n", "## Строки " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Дана строка `text` – объект Python, имеющий строковый тип, тип *string*. Проще говоря, переменная, которая содержит некоторый текст:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "text = \"А роза упала на лапу Азора\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Давайте попробуем поработать с этой строкой в формате *вопрос-ответ*." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как посчитать количество символов в строке?**" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "26" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(text) # как в списке" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как выбрать определённые символы в строке?**" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "А\n", "А роза \n" ] } ], "source": [ "print(text[0]) # тоже как в списке\n", "print(text[0:7])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как привести всё к нижнему регистру (сделать все буквы строчными?)**" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "а роза упала на лапу азора\n", "А роза упала на лапу Азора\n" ] } ], "source": [ "print(text.lower()) # метод .lower(), не забываем пустые круглые скобки\n", "print(text) # сама строка не изменяется" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "а роза упала на лапу азора\n" ] } ], "source": [ "text_low = text.lower() # создали новую строку на основе старой\n", "print(text_low)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как привести всё к верхнему регистру (сделать все буквы заглавными?)**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(text.upper())\n", "print(text)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text_up = text.upper()\n", "print(text_up)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как добавить в конец строки ещё одну строку?**" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "А роза упала на лапу Азора.\n" ] } ], "source": [ "phrase = text + \".\" # конкатенация строк\n", "print(phrase)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "А роза упала на лапу Азора. А роза упала на лапу Азора.\n" ] } ], "source": [ "phrases = phrase + \" \" + phrase\n", "print(phrases)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как убрать лишние пробелы и прочие отступы в начале и конце строки?**" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "strange = \" abc 7 \"" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "abc 7\n" ] } ], "source": [ "normal = strange.strip()\n", "print(normal)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'abc 7'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "normal" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как разбить строку на части по определённому символу?**" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['А', 'роза', 'упала', 'на', 'лапу', 'Азора']\n" ] } ], "source": [ "words = text.split() # по умолчанию разбивает по пробелу\n", "print(words)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['А роза упала ', ' лапу Азора']\n" ] } ], "source": [ "res = text.split(\"на\") # но можно указать разделитель самим\n", "print(res)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как склеить строки в одну большую строку по определённому символу?**" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "03 02 2022\n" ] } ], "source": [ "parts = [\"03\", \"02\", \"2022\"]\n", "date = \" \".join(parts) # склеиваем по пробелу\n", "print(date)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "03-02-2022\n" ] } ], "source": [ "date2 = \"-\".join(parts) # склеиваем по дефису\n", "print(date2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как проверить, что строка начинается с определённого символа?**" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text.startswith(\"а\")" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'А роза упала на лапу Азора'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text.startswith(\"А\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как проверить, что строка заканчивается на определённый символ?**" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text.endswith(\"Азора\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Как проверить, что строка содержит определённый набор символов?**" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"на\" in text # оператор in, работает не только для строк" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"ну\" in text" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 2 }