# 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>.

![](/files/-M1fbG48cS7vMGhPZQl9)

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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://george-jen.gitbook.io/data-science-and-apache-spark/python-strings.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
