Strings

Now we will learn about strings. You already know how to write them in Python code.

'This is string'
"And this is also string"

Sometimes you will need a string that is multiple lines long. But you can write strings only on one line in Python (you can actually write on more lines but the text would appear on just one).

In your text, you can use a special character that means new line \n:

print('Hello word\nHow are you?')

A backslash allows us to write characters which we can't easily write on the keyboard. The backslash also allows us to use both types of quotes in one piece of text.

print('"Don\'t do it", said dad.')
print("\"Don't do it\", said dad.")

Backward slashes can also insert exotic characters that you do not have on the keyboard. Fancy characters can be written as \N and a character name in compound ("curly") braces. Try for example the following characters (some might not work for your system):

print('--\N{LATIN SMALL LETTER L WITH STROKE}--')
print('--\N{SECTION SIGN}--')
print('--\N{PER MILLE SIGN}--')
print('--\N{BLACK STAR}--')
print('--\N{SNOWMAN}--')
print('--\N{KATAKANA LETTER TU}--')

If you want to write a backslash character in your text you have to write it twice (for example, in a path to a file in Windows). So the sequence \\ means one backslash.

print('C:\\PyLadies\\New Folder')

But back to multi-line strings. There is also another way how to write them in Python. You just have to wrap them in three single or three double quotes:

basen = '''Hello World!
How are you?'''

Programmers also use three quotes to document their functions.

def multiply(a, b):
    """ This function multiplies two arguments and returns the result.

    Both arguments should be numbers.
    """

    return a * b

Now we will have a look at how to work with strings.

Subscripting

You already know how to concatenate strings by addition and multiplication.

concatenated_string = 'a' + 'b'
long_string = 'o' * 100

Now we will learn how we can get part of a string. We will start with single characters. This is done by subscripting. The Syntax looks similar to calling a function but with square brackets.

fifth_character = 'PyLadies'[5]

print(fifth_character)

Does it work? Did you really get the fifth character?

Řešení

As you may have already noticed, programmers start counting from zero. First comes 0, then 1, and so on.

It's the same with strings - the first character is on position zero.

Why is it like that? You would have to know about pointers and arrays to fully understand, so now let's just assume that programmers are weird. Or that they just like weird numbers.

   [0] [1] [2] [3] [4] [5] [6] [7]

  ╭───┬───┬───┬───┬───┬───┬───┬───╮
  │  P │ y │ L │ a │ d │ i │ e │ s │
  ╰───┴───┴───┴───┴───┴───┴───┴───╯

What happens if you pick characters with negative numbers?

Řešení

Strings can do more tricks. You can find out how long the string is, or if it contains a certain substring.

Code Description Example
len(r) Length of string len('PyLadies')
x in r True if the string x is in the string r 'Ladies' in 'PyLadies'
x not in r The opposite of x in r 'eye' not in 'PyLadies

Python is case sensitive, so ladies in PyLadies is False. If you want to do a case insensitive test, you would have to change the case of both strings (both to lower, or both to upper) and then do x in y.

And how to change the case of our string? To do that, we will need another Python feature: methods.

Methods

Methods are like functions - we can call something with them. Unlike a function, a method is tied to some object (value). It is called by writing a colon and a method name just after the object. And then, of course, parentheses, which may contain arguments.

The String methods upper() and lower() change the case.

string = 'Hello'
print(string.upper())
print(string.lower())
print(string)

Notice that the original string has not changed. Methods return a new string and the old string stays as it was.

That is Python's standard behavior: already existing string can't be changed, we can only create a new one - derived from the old one.

Initials

For practicing methods and subscripting, try to write a program, which will ask the user for their name, then their surname and then it will print their initials - the first letters of name and surname.

Initials are always upper case (even if the user won't write it that way).

Řešení

There are many more string methods. You can find the most useful ones in our cheatsheet.

All methods are in the Python documentation.

Notice that len isn't a method but a function. It's written len(s) not r.len(). You will find out why it is like that in a minute.

Formatting

Especially useful is the format method, which replaces a pair of curly braces in string for whatever it gets as an argument.

write = '{}×{} equals {}'.format(3, 4, 3 * 4)
print(write)

The String '{}×{} equals {}' is something like a template. Imagine it as form, where we have highlighted fields where Python fills in values.

If you want to fill values in a different order, or you want the template to be clearer, you can write variables into your curly braces:

write = 'Hi {name}! The result is {number}.'.format(number=7, name='Mary')
print(write)

Formatting is used when you need to include a variable value in the string.

number = 3 + 4
name = "Mary"
write = 'Hi {}! The result is {}.'.format(name, number)
print(write)

It is almost the same as the old fashioned %s, but instead of .format you write %. If you want to use just one variable, you don't need parenthesis, just make sure that there is one space after the %.

number = 3 + 4
name = "Mary"
write = 'Hi %s! The result is %s.' % (name, number)
print(write)

Substrings

Now we will go back to subscripting. Try to find out what the following program does:

string = 'PyLadies'
substring = string[5:]
print(substring)

Keep in mind that we are still counting from 0!

Řešení

We can also use string[:5], which will select all characters up to the fifth character, which is not included. So string[:5] + string[5:] == string.

What does string[2:5] do?

And what about string[-4:]?

string = 'PyLadies'
print(string[:4])
print(string[2:5])
print(string[-4:])

You have to think about which number, which index, you want to use.

It is better to think of these numbers as being on the borderlines between characters, it makes it easier to understand:

 ╭───┬───┬───┬───┬───┬───┬───┬───╮
  │ P │ y │ L │ a │ d │ i │ e │ s │
  ├───┼───┼───┼───┼───┼───┼───┼───┤
  │   │   │   │   │   │   │   │   │
  0   1   2   3   4   5   6   7   8
 -8  -7  -6  -5  -4  -3  -2  -1

  ╰───────────────╯
  'PyLadies'[:4] == 'PyLa'

          ╰───────────────╯
        'PyLadies'[2:6] == 'Ladi'

                      ╰───────────╯
                      'PyLadies'[-3:] == 'ies'

Exercise

Try to write a function change(string, position, character).

This function returns a string which inserts the given character into the given position. The rest is the same as the original string. For example:

change('doctor', 2, 'g') == 'dogtor'
change('slice', 1, 'p') == 'spice'

Keep in mind that you can't change a string. You can only create a new one and put together pieces from the old one.

Řešení

{
  "data": {
    "sessionMaterial": {
      "id": "session-material:2018/pyladies-en-prague:tod:0",
      "title": "Strings",
      "html": "\n          \n    \n\n    <h1>Strings</h1>\n<p>Now we will learn about strings.\nYou already know how to write them in Python code.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"s1\">&apos;This is string&apos;</span>\n<span class=\"s2\">&quot;And this is also string&quot;</span>\n</pre></div><p>Sometimes you will need a string that is multiple lines long.\nBut you can write strings only on one line in Python\n(you can actually write on more lines but the text would\nappear on just one).</p>\n<p>In your text, you can use a special character that means\nnew line <code>\\n</code>:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Hello word</span><span class=\"se\">\\n</span><span class=\"s1\">How are you?&apos;</span><span class=\"p\">)</span>\n</pre></div><p>A backslash allows us to write characters which we can&apos;t easily\nwrite on the keyboard.\nThe backslash also allows us to use both types of quotes in one piece of text.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;&quot;Don</span><span class=\"se\">\\&apos;</span><span class=\"s1\">t do it&quot;, said dad.&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s2\">&quot;</span><span class=\"se\">\\&quot;</span><span class=\"s2\">Don&apos;t do it</span><span class=\"se\">\\&quot;</span><span class=\"s2\">, said dad.&quot;</span><span class=\"p\">)</span>\n</pre></div><p>Backward slashes can also insert exotic characters \nthat you do not have on the keyboard.\nFancy characters can be written as <code>\\N</code> and a character \nname in compound (&quot;curly&quot;) braces.\nTry for example the following characters\n(some might not work for your system):</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;--</span><span class=\"se\">\\N{LATIN SMALL LETTER L WITH STROKE}</span><span class=\"s1\">--&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;--</span><span class=\"se\">\\N{SECTION SIGN}</span><span class=\"s1\">--&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;--</span><span class=\"se\">\\N{PER MILLE SIGN}</span><span class=\"s1\">--&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;--</span><span class=\"se\">\\N{BLACK STAR}</span><span class=\"s1\">--&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;--</span><span class=\"se\">\\N{SNOWMAN}</span><span class=\"s1\">--&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;--</span><span class=\"se\">\\N{KATAKANA LETTER TU}</span><span class=\"s1\">--&apos;</span><span class=\"p\">)</span>\n</pre></div><p>If you want to write a backslash character in your text\nyou have to write it twice (for example, in a path to a\nfile in Windows).\nSo the sequence <code>\\\\</code> means one backslash.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;C:</span><span class=\"se\">\\\\</span><span class=\"s1\">PyLadies</span><span class=\"se\">\\\\</span><span class=\"s1\">New Folder&apos;</span><span class=\"p\">)</span>\n</pre></div><p>But back to multi-line strings. There is also another way how to write them\nin Python. You just have to wrap them in <em>three</em> single\nor <em>three</em> double quotes:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">basen</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;&apos;&apos;Hello World!</span>\n<span class=\"s1\">How are you?&apos;&apos;&apos;</span>\n</pre></div><p>Programmers also use three quotes to document their functions.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">multiply</span><span class=\"p\">(</span><span class=\"n\">a</span><span class=\"p\">,</span> <span class=\"n\">b</span><span class=\"p\">):</span>\n    <span class=\"sd\">&quot;&quot;&quot; This function multiplies two arguments and returns the result.</span>\n\n<span class=\"sd\">    Both arguments should be numbers.</span>\n<span class=\"sd\">    &quot;&quot;&quot;</span>\n\n    <span class=\"k\">return</span> <span class=\"n\">a</span> <span class=\"o\">*</span> <span class=\"n\">b</span>\n</pre></div><p>Now we will have a look at how to work with strings.</p>\n<h2>Subscripting</h2>\n<p>You already know how to concatenate strings by addition and multiplication.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">concatenated_string</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;a&apos;</span> <span class=\"o\">+</span> <span class=\"s1\">&apos;b&apos;</span>\n<span class=\"n\">long_string</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;o&apos;</span> <span class=\"o\">*</span> <span class=\"mi\">100</span>\n</pre></div><p>Now we will learn how we can get part of a string.\nWe will start with single characters.\nThis is done by <em>subscripting</em>. The Syntax looks similar\nto calling a function but with square brackets.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">fifth_character</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;PyLadies&apos;</span><span class=\"p\">[</span><span class=\"mi\">5</span><span class=\"p\">]</span>\n\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">fifth_character</span><span class=\"p\">)</span>\n</pre></div><p>Does it work? Did you really get the fifth character?</p>\n<div class=\"solution\" id=\"solution-0\">\n    <h3>&#x158;e&#x161;en&#xED;</h3>\n    <div class=\"solution-cover\">\n        <a href=\"/2018/pyladies-en-prague/beginners-en/str/index/solutions/0/\"><span class=\"link-text\">Uk&#xE1;zat &#x159;e&#x161;en&#xED;</span></a>\n    </div>\n    <div class=\"solution-body\" aria-hidden=\"true\">\n        <p>You didn&apos;t &#x2013; you got the <em>sixth</em> character.</p>\n    </div>\n</div><p>As you may have already noticed, programmers start counting from zero.\nFirst comes 0, then 1, and so on.</p>\n<p>It&apos;s the same with strings - the first character is on position zero.</p>\n<p>Why is it like that?\nYou would have to know about pointers and arrays\nto fully understand, so now let&apos;s just assume\nthat programmers are weird. Or that they just like\nweird numbers.</p>\n<div class=\"highlight\"><pre><code>   [0] [1] [2] [3] [4] [5] [6] [7]\n\n  &#x256D;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x256E;\n  &#x2502;  P &#x2502; y &#x2502; L &#x2502; a &#x2502; d &#x2502; i &#x2502; e &#x2502; s &#x2502;\n  &#x2570;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x256F;</code></pre></div><p>What happens if you pick characters with negative numbers?</p>\n<div class=\"solution\" id=\"solution-1\">\n    <h3>&#x158;e&#x161;en&#xED;</h3>\n    <div class=\"solution-cover\">\n        <a href=\"/2018/pyladies-en-prague/beginners-en/str/index/solutions/1/\"><span class=\"link-text\">Uk&#xE1;zat &#x159;e&#x161;en&#xED;</span></a>\n    </div>\n    <div class=\"solution-body\" aria-hidden=\"true\">\n        <div class=\"highlight\"><pre><span></span><span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;PyLadies&apos;</span><span class=\"p\">[</span><span class=\"o\">-</span><span class=\"mi\">1</span><span class=\"p\">])</span>  <span class=\"c1\"># &#x2192; s</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;PyLadies&apos;</span><span class=\"p\">[</span><span class=\"o\">-</span><span class=\"mi\">2</span><span class=\"p\">])</span>  <span class=\"c1\"># &#x2192; e</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;PyLadies&apos;</span><span class=\"p\">[</span><span class=\"o\">-</span><span class=\"mi\">3</span><span class=\"p\">])</span>  <span class=\"c1\"># &#x2192; i</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;PyLadies&apos;</span><span class=\"p\">[</span><span class=\"o\">-</span><span class=\"mi\">4</span><span class=\"p\">])</span>  <span class=\"c1\"># &#x2192; d</span>\n</pre></div><p>Negative numbers pick characters from the end.</p>\n<div class=\"highlight\"><pre><code>   [0] [1] [2] [3] [4] [5] [6] [7]\n   [-8][-7][-6][-5][-4][-3][-2][-1]\n  &#x256D;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x256E;\n  &#x2502;  P &#x2502; y &#x2502; L &#x2502; a &#x2502; d &#x2502; i &#x2502; e &#x2502; s &#x2502;\n  &#x2570;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x2534;&#x2500;&#x2500;&#x2500;&#x256F;</code></pre></div>\n    </div>\n</div><p>Strings can do more tricks.\nYou can find out how long the string is,\nor if it contains a certain substring.</p>\n<table class=\"table\">\n    <tbody><tr>\n        <th>Code</th>\n        <th>Description</th>\n        <th>Example</th>\n    </tr>\n    <tr>\n        <td><code>len(r)</code></td>\n        <td>Length of string</td>\n        <td><code>len(&apos;PyLadies&apos;)</code></td>\n    </tr>\n    <tr>\n        <td><code>x&#xA0;in&#xA0;r</code></td>\n        <td>True if the string <code>x</code> is in the string <code>r</code></td>\n        <td><code>&apos;Ladies&apos; in &apos;PyLadies&apos;</code></td>\n    </tr>\n    <tr>\n        <td><code>x&#xA0;not&#xA0;in&#xA0;r</code></td>\n        <td>The opposite of <code>x in r</code></td>\n        <td><code>&apos;eye&apos; not in &apos;PyLadies</code></td>\n    </tr>\n</tbody></table><p>Python is case sensitive, so <code>ladies in PyLadies</code>\nis <code>False</code>. If you want to do a case insensitive test,\nyou would have to change the case of both strings \n(both to lower, or both to upper) and then do <code>x in y</code>.</p>\n<p>And how to change the case of our string?\nTo do that, we will need another Python feature: methods.</p>\n<h2>Methods</h2>\n<p><em>Methods</em> are like functions - we can call something with them.\nUnlike a function, a method is tied to some <em>object</em> (value).\nIt is called by writing a colon and a method name just after the object.\nAnd then, of course, parentheses, which may contain arguments.</p>\n<p>The String methods <code>upper()</code> and <code>lower()</code> change the case.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">string</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Hello&apos;</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"o\">.</span><span class=\"n\">upper</span><span class=\"p\">())</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"o\">.</span><span class=\"n\">lower</span><span class=\"p\">())</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"p\">)</span>\n</pre></div><div class=\"admonition note\"><p>Notice that the original string has not changed.\nMethods return a new string and the old string stays\nas it was.</p>\n<p>That is Python&apos;s standard behavior: already existing string can&apos;t be changed,\nwe can only create a new one - derived from the old one.</p>\n</div><h3>Initials</h3>\n<p>For practicing methods and subscripting, try to write a program,\nwhich will ask the user for their name, then their surname\nand then it will print their initials - the first letters of\nname and surname.</p>\n<p>Initials are always upper case (even if the\nuser won&apos;t write it that way).</p>\n<div class=\"solution\" id=\"solution-2\">\n    <h3>&#x158;e&#x161;en&#xED;</h3>\n    <div class=\"solution-cover\">\n        <a href=\"/2018/pyladies-en-prague/beginners-en/str/index/solutions/2/\"><span class=\"link-text\">Uk&#xE1;zat &#x159;e&#x161;en&#xED;</span></a>\n    </div>\n    <div class=\"solution-body\" aria-hidden=\"true\">\n        <div class=\"highlight\"><pre><span></span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter your name: &apos;</span><span class=\"p\">)</span>\n<span class=\"n\">surname</span> <span class=\"o\">=</span> <span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter your surname: &apos;</span><span class=\"p\">)</span>\n<span class=\"n\">initials</span> <span class=\"o\">=</span> <span class=\"n\">name</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"n\">surname</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Initials:&apos;</span><span class=\"p\">,</span> <span class=\"n\">initials</span><span class=\"o\">.</span><span class=\"n\">upper</span><span class=\"p\">())</span>\n</pre></div><p>There are more ways how to write such a program.\nYou can call <code>upper()</code> twice - on name and surname separately.</p>\n<p>Or like this:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter your name: &apos;</span><span class=\"p\">)</span>\n<span class=\"n\">surname</span> <span class=\"o\">=</span> <span class=\"nb\">input</span><span class=\"p\">(</span><span class=\"s1\">&apos;Enter your surname: &apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"s1\">&apos;Initials:&apos;</span><span class=\"p\">,</span> <span class=\"p\">(</span><span class=\"n\">name</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"n\">surname</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])</span><span class=\"o\">.</span><span class=\"n\">upper</span><span class=\"p\">())</span>\n</pre></div><p>I recommend the first option. It is longer but way more clear.</p>\n    </div>\n</div><p>There are many more string methods. You can find the most\nuseful ones in our <a href=\"https://github.com/muzikovam/cheatsheets/blob/master/strings/strings-en.pdf\">cheatsheet</a>.</p>\n<p>All methods are in the <a href=\"https://docs.python.org/3/library/stdtypes.html#string-methods\">Python documentation</a>.</p>\n<p>Notice that <code>len</code> isn&apos;t a method but a function. It&apos;s\nwritten <code>len(s)</code> not <code>r.len()</code>.\nYou will find out why it is like that in a minute.</p>\n<h2>Formatting</h2>\n<p>Especially useful is the <code>format</code> method, which replaces\na pair of curly braces in string for whatever it\ngets as an argument.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">write</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;{}&#xD7;{} equals {}&apos;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"mi\">3</span><span class=\"p\">,</span> <span class=\"mi\">4</span><span class=\"p\">,</span> <span class=\"mi\">3</span> <span class=\"o\">*</span> <span class=\"mi\">4</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">write</span><span class=\"p\">)</span>\n</pre></div><p>The String <code>&apos;{}&#xD7;{} equals {}&apos;</code> is something like a <em>template</em>.\nImagine it as form, where we have highlighted fields where Python\nfills in values.</p>\n<p>If you want to fill values in a different order, or you want\nthe template to be clearer, you can write variables into your\ncurly braces:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">write</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Hi {name}! The result is {number}.&apos;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"n\">number</span><span class=\"o\">=</span><span class=\"mi\">7</span><span class=\"p\">,</span> <span class=\"n\">name</span><span class=\"o\">=</span><span class=\"s1\">&apos;Mary&apos;</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">write</span><span class=\"p\">)</span>\n</pre></div><p>Formatting is used when you need to include a variable value in\nthe string.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">number</span> <span class=\"o\">=</span> <span class=\"mi\">3</span> <span class=\"o\">+</span> <span class=\"mi\">4</span>\n<span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s2\">&quot;Mary&quot;</span>\n<span class=\"n\">write</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Hi {}! The result is {}.&apos;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"n\">name</span><span class=\"p\">,</span> <span class=\"n\">number</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">write</span><span class=\"p\">)</span>\n</pre></div><p>It is almost the same as the old fashioned <code>%s</code>, but instead of <code>.format</code>\nyou write <code>%</code>. If you want to use just one variable, you don&apos;t\nneed parenthesis, just make sure that there is one space after the <code>%</code>.</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">number</span> <span class=\"o\">=</span> <span class=\"mi\">3</span> <span class=\"o\">+</span> <span class=\"mi\">4</span>\n<span class=\"n\">name</span> <span class=\"o\">=</span> <span class=\"s2\">&quot;Mary&quot;</span>\n<span class=\"n\">write</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;Hi </span><span class=\"si\">%s</span><span class=\"s1\">! The result is </span><span class=\"si\">%s</span><span class=\"s1\">.&apos;</span> <span class=\"o\">%</span> <span class=\"p\">(</span><span class=\"n\">name</span><span class=\"p\">,</span> <span class=\"n\">number</span><span class=\"p\">)</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">write</span><span class=\"p\">)</span>\n</pre></div><h2>Substrings</h2>\n<p>Now we will go back to subscripting.\nTry to find out what the following program does:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">string</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;PyLadies&apos;</span>\n<span class=\"n\">substring</span> <span class=\"o\">=</span> <span class=\"n\">string</span><span class=\"p\">[</span><span class=\"mi\">5</span><span class=\"p\">:]</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">substring</span><span class=\"p\">)</span>\n</pre></div><div class=\"admonition warning\"><p>Keep in mind that we are still counting from 0!</p>\n</div><div class=\"solution\" id=\"solution-3\">\n    <h3>&#x158;e&#x161;en&#xED;</h3>\n    <div class=\"solution-cover\">\n        <a href=\"/2018/pyladies-en-prague/beginners-en/str/index/solutions/3/\"><span class=\"link-text\">Uk&#xE1;zat &#x159;e&#x161;en&#xED;</span></a>\n    </div>\n    <div class=\"solution-body\" aria-hidden=\"true\">\n        <p><code>string[5:]</code> will print the <em>substring</em> from the fifth character to the end.</p>\n    </div>\n</div><p>We can also use <code>string[:5]</code>, which will select all characters\nup to the fifth character, which is not included.\nSo <code>string[:5] + string[5:] == string</code>.</p>\n<p>What does <code>string[2:5]</code> do?</p>\n<p>And what about <code>string[-4:]</code>?</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">string</span> <span class=\"o\">=</span> <span class=\"s1\">&apos;PyLadies&apos;</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"p\">[:</span><span class=\"mi\">4</span><span class=\"p\">])</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"p\">[</span><span class=\"mi\">2</span><span class=\"p\">:</span><span class=\"mi\">5</span><span class=\"p\">])</span>\n<span class=\"k\">print</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"p\">[</span><span class=\"o\">-</span><span class=\"mi\">4</span><span class=\"p\">:])</span>\n</pre></div><p>You have to think about which number, which <em>index</em>, you want to use.</p>\n<p>It is better to think of these numbers as being on the borderlines \nbetween characters, it makes it easier to understand:</p>\n<p><a id=\"slicing-diagram\"></a></p>\n<div class=\"highlight\"><pre><code> &#x256D;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x252C;&#x2500;&#x2500;&#x2500;&#x256E;\n  &#x2502; P &#x2502; y &#x2502; L &#x2502; a &#x2502; d &#x2502; i &#x2502; e &#x2502; s &#x2502;\n  &#x251C;&#x2500;&#x2500;&#x2500;&#x253C;&#x2500;&#x2500;&#x2500;&#x253C;&#x2500;&#x2500;&#x2500;&#x253C;&#x2500;&#x2500;&#x2500;&#x253C;&#x2500;&#x2500;&#x2500;&#x253C;&#x2500;&#x2500;&#x2500;&#x253C;&#x2500;&#x2500;&#x2500;&#x253C;&#x2500;&#x2500;&#x2500;&#x2524;\n  &#x2502;   &#x2502;   &#x2502;   &#x2502;   &#x2502;   &#x2502;   &#x2502;   &#x2502;   &#x2502;\n  0   1   2   3   4   5   6   7   8\n -8  -7  -6  -5  -4  -3  -2  -1\n\n  &#x2570;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x256F;\n  &apos;PyLadies&apos;[:4] == &apos;PyLa&apos;\n\n          &#x2570;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x256F;\n        &apos;PyLadies&apos;[2:6] == &apos;Ladi&apos;\n\n                      &#x2570;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x2500;&#x256F;\n                      &apos;PyLadies&apos;[-3:] == &apos;ies&apos;</code></pre></div><h2>Exercise</h2>\n<p>Try to write a function <code>change(string, position, character)</code>.</p>\n<p>This function returns a string which inserts the given character into the given\nposition. The rest is the same as the original <code>string</code>.\nFor example:</p>\n<div class=\"highlight\"><pre><span></span><span class=\"n\">change</span><span class=\"p\">(</span><span class=\"s1\">&apos;doctor&apos;</span><span class=\"p\">,</span> <span class=\"mi\">2</span><span class=\"p\">,</span> <span class=\"s1\">&apos;g&apos;</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;dogtor&apos;</span>\n<span class=\"n\">change</span><span class=\"p\">(</span><span class=\"s1\">&apos;slice&apos;</span><span class=\"p\">,</span> <span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"s1\">&apos;p&apos;</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"s1\">&apos;spice&apos;</span>\n</pre></div><p>Keep in mind that you can&apos;t change a string.\nYou can only create a new one and put together\npieces from the old one.</p>\n<div class=\"solution\" id=\"solution-4\">\n    <h3>&#x158;e&#x161;en&#xED;</h3>\n    <div class=\"solution-cover\">\n        <a href=\"/2018/pyladies-en-prague/beginners-en/str/index/solutions/4/\"><span class=\"link-text\">Uk&#xE1;zat &#x159;e&#x161;en&#xED;</span></a>\n    </div>\n    <div class=\"solution-body\" aria-hidden=\"true\">\n        <div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">change</span><span class=\"p\">(</span><span class=\"n\">string</span><span class=\"p\">,</span> <span class=\"n\">position</span><span class=\"p\">,</span> <span class=\"n\">character</span><span class=\"p\">):</span>\n    <span class=\"sd\">&quot;&quot;&quot;This function inserts the given character into the given position.</span>\n\n<span class=\"sd\">    Returns a new string which has the given character in the given</span>\n<span class=\"sd\">    position. The rest is the same as the original string.</span>\n<span class=\"sd\">    &quot;&quot;&quot;</span>\n\n    <span class=\"k\">return</span> <span class=\"n\">string</span><span class=\"p\">[:</span><span class=\"n\">position</span><span class=\"p\">]</span> <span class=\"o\">+</span> <span class=\"n\">character</span> <span class=\"o\">+</span> <span class=\"n\">string</span><span class=\"p\">[</span><span class=\"n\">position</span> <span class=\"o\">+</span> <span class=\"mi\">1</span><span class=\"p\">:]</span>\n</pre></div>\n    </div>\n</div>\n\n\n        "
    }
  }
}