# Strings

### Strings

NOT mutable, change a string variable result in a new string

Need single or double quotes “” or ‘’ to enclose, for example: “Hello World” or ‘Hello World’, case sensitive

String is a sequence, iterable

s=‘abc’

s\[0]=“a”

s\[1]=“b”

s\[2]=“c”

It is zero based indexing, index starts from zero

String can be iterated through:

```
for i in “abc”:
    print(i)
```

Convert to string, use function str()

For example:

n=12345

str(n) becomes “12345”

String is an object, meaning it has methods and attributes that can be invoked

To see all methods, type

help(\<string variable>)

In Jupyter notebook, to see list of methods or attributes

Press shift key after enter \<string variable>.

![](https://2100080250-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1PNTHVApkPePuMdTu3%2F-M1dwpEzXF10aXtFA6El%2F-M1fbG48cS7vMGhPZQl9%2Fpython_str.jpg?alt=media\&token=cae10818-e660-4330-a00f-d5b3483f8046)

Strings are can be in single quote (‘) or double quotes (“)

\>>> 'spam eggs' # single quotes

'spam eggs’

\>>> 'doesn\\'t' # use " to escape the single quote...

"doesn’t”

\>>> "doesn't" # ...or use double quotes instead

"doesn’t”

\>>> '"Yes," they said.'

\#Use single quote to include double quote

'"Yes," they said.’

\>>> "\\"Yes,\\" they said." #use back slash to escape quote mark

'"Yes," they said.’

\#use + to concatenate 2 strings

\>>>”Hello”+” World”&#x20;

Hello World

Strings can be indexed (sub-scripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:

\>>>Word=“Hello World”

\>>>Word\[0]

‘H’

\>>>Word\[9]

‘d’

\>>>Word\[-1]

\#Slicing

‘d’

\>>>Word\[-11]

‘H’

\>>>Word\[0:]

‘Hello World’

\>>>Word\[:9]

‘Hello World’ #character at index 9 is not included.
