{ "cells": [ { "cell_type": "markdown", "id": "645954ef-4333-4844-bf35-884e17142a77", "metadata": {}, "source": [ "# Strings\n", "\n", "## `str` data type\n", "\n", "Previously, we have already seen the data type for strings in Python. Today, we will take a closer look at them and learn about their new features.\n", "Strings come with some helpful built-in functions, often called methods, that let you perform various operations on them. \n", "\n", "### Methods\n", "Here are a few common ones (the full list of methods you can find here):\n", "- `upper()`: Transforms all characters to uppercase.\n", "- `lower()`: Converts all characters to lowercase.\n", "- `replace()`: Substitutes one part of the string with another.\n", "- `split()`: Breaks the string into a list using a separator." ] }, { "cell_type": "code", "execution_count": null, "id": "4600f11f-3e76-4849-aaac-8a887a7cc621", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "text = \"Random text\"\n", "upper_text = text.upper()\n", "lower_text = text.lower()\n", "repl_text = text.replace(\"Random\", \"Non-random\")\n", "words = text.split()\n", "\n", "print(\"upper_text:\", upper_text)\n", "print(\"lower_text:\", lower_text)\n", "print(\"repl_text:\", repl_text)\n", "print(\"words:\", words)" ] }, { "cell_type": "markdown", "id": "72e2bcb3-896a-4b68-96f2-a5c42c0a2a75", "metadata": {}, "source": [ "An important note is that strings are immutable objects. In all cases of method usage, we did not modify the original string." ] }, { "cell_type": "code", "execution_count": null, "id": "cf883ba0-f623-453c-8610-f72ec6d747f1", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "print(text)" ] }, { "cell_type": "markdown", "id": "1d9c5108-6db7-40fb-8101-06be053de112", "metadata": {}, "source": [ "We can determine the length of a string using the same method as we did with lists. Additionally, we can use indexing:" ] }, { "cell_type": "code", "execution_count": null, "id": "6d371b99-1c7e-45ac-a099-4c9a00400825", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "for i in range(len(text)):\n", " print(str(i) + \": \" + text[i])" ] }, { "cell_type": "markdown", "id": "48bd1b82-9d01-4e07-92e9-afd22e75f9ed", "metadata": {}, "source": [ "Since strings are immutable, we cannot reassign specific elements.\n", "```python\n", "text = \"Random text\"\n", "text[0] = \"W\"\n", "```\n", "\n", "```\n", "TypeError: 'str' object does not support item assignment\n", "```\n", "\n", "### Converting a List to a String\n", "\n", "If you have a list and want to turn it into a single string, you can use the join() method. This method joins the elements of a list into a single string, with a specified separator in between." ] }, { "cell_type": "code", "execution_count": null, "id": "a0ad0b6f-74a0-43ba-9079-592433ddb1b1", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "fruit_string = \"_\".join(fruits)\n", "print(fruit_string)" ] }, { "cell_type": "markdown", "id": "fdf96757-005b-46aa-8083-8fa3dca8a200", "metadata": {}, "source": [ "### Converting a String to a List\n", "\n", "If you have a string and want to split it into a list of elements, you can use the split() method. This method breaks the string into parts using a specified separator." ] }, { "cell_type": "code", "execution_count": null, "id": "31d96154-2ccb-4168-8ed6-273988c26786", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "fruit_string = \"apple, banana, cherry\"\n", "fruits = fruit_string.split(\", \")\n", "print(fruits)" ] }, { "cell_type": "markdown", "id": "6aa55049-03ca-45c3-bfa4-3c733cd21212", "metadata": {}, "source": [ "If you want to create a list where each symbol is a separate element, you can use the following approach:" ] }, { "cell_type": "code", "execution_count": null, "id": "6214507d-f93b-47a6-856c-8f425bc56f38", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "name_str = \"Vladimir\"\n", "name_list = list(name_str)\n", "print(name_list)" ] }, { "cell_type": "markdown", "id": "628215df-936d-4894-87ec-072972e8b6f8", "metadata": {}, "source": [ "## `f`-Strings (Strings Formatting)\n", "\n", "Imagine you're writing a letter, and you need to fill in details like the recipient's name, the date, and the subject. \n", "It would be cumbersome to write everything from scratch every time, wouldn’t it? \n", "In programming, we often face similar situations where we need to combine text with dynamic values like variables. \n", "Enter **f-strings** - a feature in Python that makes this task easy, efficient, and even a little bit fun!\n", "\n", "f-strings (formatted string literals) were introduced in Python 3.6 and have since become a favorite tool for many developers.\n", "They allow you to easily embed expressions inside string literals, using `{}` braces. \n", "Not only do f-strings make your code more readable, but they also make it more powerful and concise.\n", "\n", "```{note}\n", "Why Use f-Strings?\n", "\n", "\n", "- **Simplicity**: They’re straightforward and easy to understand.\n", "- **Readability**: They make your code cleaner and more readable.\n", "- **Efficiency**: They’re faster than older methods like `str.format()` and `%` formatting.\n", "- **Versatility**: You can embed any valid Python expression inside the braces.\n", "```\n", "\n", "### Basic Usage of f-Strings\n", "\n", "Let’s start with a simple example. Suppose you want to print a sentence that includes a person’s name and age:" ] }, { "cell_type": "code", "execution_count": null, "id": "b165af22-7326-4b4c-8c48-dae3edfde3a7", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "name = \"Alice\"\n", "age = 30\n", "print(f\"My name is {name} and I am {age} years old.\")" ] }, { "cell_type": "markdown", "id": "ff0b5408-6225-4358-96b0-d1d36bd3b435", "metadata": {}, "source": [ "**What’s Happening?**\n", "- The `f` before the string tells Python to treat it as a formatted string literal.\n", "- Inside the curly braces `{}`, you can put any variable, and Python will replace it with its value.\n", "\n", "### Embedding Expressions\n", "\n", "f-strings aren’t just for variables; you can also include expressions. For example:" ] }, { "cell_type": "code", "execution_count": null, "id": "ea8ffc24-72bb-4f5d-9056-adf9b7c1278d", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "a = 5\n", "b = 10\n", "print(f\"The sum of {a} and {b} is {a + b}.\")\n" ] }, { "cell_type": "markdown", "id": "a986a2dc-a391-4a6b-a9a7-c1fa552b6ddd", "metadata": {}, "source": [ "**What’s Happening?**\n", "- Inside the curly braces, you’re performing the calculation `{a + b}`, and Python evaluates this expression before embedding the result into the string.\n", "\n", "### Formatting Numbers with f-Strings\n", "\n", "f-strings are also incredibly useful when you need to format numbers. Let’s say you want to display a price with two decimal places:" ] }, { "cell_type": "code", "execution_count": null, "id": "f6e63b44-a248-4658-891a-2b15a5bf9f1d", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "price = 49.12345\n", "print(f\"The price is {price:.2f}\")" ] }, { "cell_type": "markdown", "id": "28ee0e03-09f7-4cab-9e09-f5fae9be78c2", "metadata": {}, "source": [ "**Breaking It Down:**\n", "- `{price:.2f}`: Here, `.2f` tells Python to format the number to 2 decimal places.\n", "\n", "You can even add commas to large numbers:" ] }, { "cell_type": "code", "execution_count": null, "id": "2eea4390-e4ca-44da-8cc6-0bdc3faa65b4", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "big_number = 1000000\n", "print(f\"The big number is {big_number:,}\")" ] }, { "cell_type": "markdown", "id": "4dad8697-72f4-403c-8651-3441716a3c91", "metadata": {}, "source": [ "**What’s Happening?**\n", "- `{big_number:,}`: The comma inside the braces tells Python to include commas as thousand separators.\n", "\n", "\n", "### Multiline f-Strings\n", "\n", "What if you want to create a string that spans multiple lines? No problem! f-strings support multiline formatting:" ] }, { "cell_type": "code", "execution_count": null, "id": "9c6c7614-0817-45a8-a4d3-c11e86911c7d", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "name = \"Alice\"\n", "age = 30\n", "address = \"123 Maple Street\"\n", "\n", "info = (\n", " f\"Name: {name}\\n\"\n", " f\"Age: {age}\\n\"\n", " f\"Address: {address}\\n\"\n", ")\n", "\n", "print(info)" ] }, { "cell_type": "markdown", "id": "f8aec1fa-34c9-4944-9338-2fea76f67520", "metadata": {}, "source": [ "**What’s Happening?**\n", "- The parentheses `()` allow you to split the f-string across multiple lines for better readability.\n", "- Each line in the f-string is treated as part of the overall string.\n", "\n", "### f-Strings with Dictionaries\n", "\n", "You can even use f-strings to access values in dictionaries. Imagine you have a dictionary with some data:" ] }, { "cell_type": "code", "execution_count": null, "id": "5dc640df-ba1c-4e24-8f51-2767a50c33f4", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "person = {\n", " \"name\": \"Alice\",\n", " \"age\": 30,\n", " \"city\": \"Wonderland\"\n", "}\n", "\n", "print(f\"{person['name']} is {person['age']} years old and lives in {person['city']}.\")" ] }, { "cell_type": "markdown", "id": "8d8fbfe6-13c8-4b4c-829e-aca6a58aec6a", "metadata": {}, "source": [ "**What’s Happening?**\n", "- You’re directly accessing the dictionary values inside the f-string by using the key names.\n", "\n", "### Advanced: Nesting f-Strings\n", "\n", "For the adventurous, you can even nest f-strings, though it’s a bit rare. Let’s see a quick example:" ] }, { "cell_type": "code", "execution_count": null, "id": "b2676b47-831e-47c2-9758-b6021fe18af3", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "value = 4.56789\n", "precision = 2\n", "print(f\"Value rounded to {precision} decimal places is {value:.{precision}f}.\")" ] }, { "cell_type": "markdown", "id": "91946452-1a02-46ee-81d7-b095f0ff7854", "metadata": {}, "source": [ "**What’s Happening?**\n", "- `{value:.{precision}f}`: Here, the `precision` variable controls how many decimal places are shown.\n", "\n", "\n", "```{note}\n", "f-strings are one of those features in Python that, once you start using, you’ll wonder how you ever lived without them. \n", "They’re not just about inserting variables into strings—they’re a powerful tool for formatting, calculating, and displaying data in a way that’s both readable and efficient.\n", "\n", "As you continue coding in Python, you’ll find that f-strings become your best friend for handling strings. \n", "Whether you’re generating reports, creating logs, or just printing a message to the screen, f-strings make your code cleaner and more powerful.\n", "\n", "```" ] }, { "cell_type": "markdown", "id": "66cb2ce9-3204-4dc0-aeee-8aa4dc0167cb", "metadata": {}, "source": [ "## Similarities between lists, tuples, and strings\n", "Despite their differences, lists, strings, and tuples also share some common features.\n", "\n", "- **One common feature is that they all have a length, which can be obtained using the `len` function:**" ] }, { "cell_type": "code", "execution_count": null, "id": "036cfbc8-a1e8-44da-9db9-18de79181f23", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "line = \"The happiness of your life depends upon the quality of your thoughts.\"\n", "numbers = [i * 10 for i in range(10)]\n", "configs = (1920, 1080, \"Windows\")\n", "\n", "print(len(line)) # number of symbols\n", "print(len(numbers)) # number of elements \n", "print(len(configs)) # number of elements" ] }, { "cell_type": "markdown", "id": "46407c7f-2b99-4526-95cf-be75572535bd", "metadata": {}, "source": [ "- **Lists, strings, and tuples are iterable objects, allowing iteration over them using a `for` loop:**" ] }, { "cell_type": "code", "execution_count": null, "id": "ff96744e-fb1b-4583-abd7-888dbe404779", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "for elem in line:\n", " print(elem, end=\"\")\n", "print()\n", "\n", "for elem in numbers:\n", " print(elem, end=\" \")\n", "print()\n", "\n", "for elem in configs:\n", " print(elem, end=\" \")\n", "print()" ] }, { "cell_type": "markdown", "id": "150530f1-dd89-4761-b40e-e62e0633faf6", "metadata": {}, "source": [ "Here we use an additional `end` argument in the `print` function, which allows us to replace the default new line symbol `\\n` with a custom one.\n", "\n", "- **We can check whether an element or substring is part of a list, tuple, or string by using the `in` operator:**" ] }, { "cell_type": "code", "execution_count": null, "id": "b4ca330b-b7cf-4451-989c-2dd65f85ca1e", "metadata": { "tags": [ "hide-output" ] }, "outputs": [], "source": [ "print(\"happiness\" in line)\n", "print(10 in numbers)\n", "print(1920 in configs)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.12.4" } }, "nbformat": 4, "nbformat_minor": 5 }