---
jupytext:
  formats: content_md///md:myst,content///ipynb
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.13.8
kernelspec:
  display_name: Python 3 (ipykernel)
  language: python
  name: python3
---

(python:strings:basics)=
# Basics

## Substrings

Strings are sequence-type objects, that is, they can be regarded as lists of characters. Each character then is itself a string object.

```{code-cell} ipython3
a = 'some string'
print(a[0])
print(a[1])
print(len(a))
```

Even slicing is possible.

```{code-cell} ipython3
b = a[2:8]
print(b)
```

Remember that strings are immutable. Thus, `a[3] = 'x'` does not replace the fourth character of `a` by `x`, but leads to an error message.

## Line Breaks in String Literals

Sometimes it's necessary to use line breaks when specifying strings in source code. For this purpose Python knows triple quotes.

```{code-cell} ipython3
a = '''a very long string
spanning several lines
in source code'''

b = """another very long string
spanning several lines
in source code"""

print(a)
print(b)
```

As we see, line breaks in source code become part of the string. If this behavior is not desired, end each line with `\`.

```{code-cell} ipython3
a = '''a very long string\
spanning several lines\
in source code'''

print(a)
```

A common pattern in Python source files is

```{code-cell} ipython3
a = '''\
first line
second line
last line\
'''
print(a)
```

This way we get one-to-one correspondence between source code and screen output.

```{note}
A trailing `\` tells Python that the souce code line continues on the next line, that is, that the next line break is not to be considered as line break. Usage is not restricted to strings. Long source code lines (longer than 80 characters) should be wrapped to multiple short lines.
```

## Raw Strings

To have line breaks and special characters in string literals we have to use escape sequences like `\n`, `\"`, and so on. If we want to prevent the Python interpreter from translating escape sequences into corresponding characters, we may use *raw strings*. A raw string is taken as is by the interpreter. To mark a string literal as raw string prepend `r`.

```{code-cell} ipython3
a = r'Here is a line break:\nNow we are on a new line'
print(a)
print(type(a))
```

## Useful Member Functions

Read Python's documentation of
* [`count`](https://docs.python.org/3/library/stdtypes.html#str.count)
* [`find`](https://docs.python.org/3/library/stdtypes.html#str.find)
* [`replace`](https://docs.python.org/3/library/stdtypes.html#str.replace)
* [`split`](https://docs.python.org/3/library/stdtypes.html#str.split)
* [`upper`](https://docs.python.org/3/library/stdtypes.html#str.upper)
* [`is...`](https://docs.python.org/3/library/stdtypes.html#str.isalnum)

to get an idea of what's possible with string methods.
