> For the complete documentation index, see [llms.txt](https://lei-d.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lei-d.gitbook.io/leetcode/data-structure/string.md).

# String

Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and doc strings.

```python
string = "Hello world!"
print string
# Hello world!

mystring = '''first line 
second line
third line'''
print mystring
# first line 
# second line
# third line

print('''He said, "What's there?"''')
# He said, "What's there?"            # using triple quotes

print('He said, "What\'s there?"')
# He said, "What's there?"            # escaping single quotes

print("He said, \"What's there?\"")
# He said, "What's there?"            # escaping double quotes
```

**Convert from other type with** `str()`

```python
#convert from integer to string
str(1)
```

**Slicing:** similar as in list

```python
string = "Hello world!"
print string[3]
# l                   # return the 4th character
print string[3:7]
# lo w                # return the 4th to 7th character
print string[:7]
# Hello w             # from the beginning to the 7th character
print string[3:]
# lo world!           # from the 4th to the end
print string[-3:]
# ld!                 # 3rd character from the end until the end
print string[3:8:2]
# l o                 # [start:stop:step]
```

**Reverse**

Note that reverse() doesn't work for string. Need to convert string to list and then reverse().

```python
print string[::-1]
# !dlrow olleH
```

Important: **We can't do slicing and reverse simultaneously**. If we want to reverse a substring:

```python
string[start:end][::-1]
```

**Change a string**

Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. We can simply reassign different strings to the same name.

```python
string = "Hello world!"
string[0] = "h"
print string
# TypeError: 'str' object does not support item assignment

string = "hello world!"
print string
# hello world!
```

**Delete characters from a string**

We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword

`del.`

```python
string = "hello world!"
print string
# hello world!
del string
print string
# NameError: name 'string' is not defined
```

**Concatenation of Two or More Strings**

Joining of two or more strings into a single one is called concatenation.

The `+` operator does this in Python. Simply writing two string literals together also concatenates them.

The `*` operator can be used to repeat the string for a given number of times.

```python
string1 = "hello"
string2 = "world"

print string1 + string2
# helloworld

whole = string1 + " " + string2
print whole
# hello world

print string1 * 2 + " " + string2
# hellohello world
```

**String Membership Test**

We can test if a sub string exists within a string or not, using the keyword`in`.

```python
print "l" in "hello"
# True

print "l" not in "hello"
# False
```

**String Comparison**

We can use == to compare if two strings are the same.

```python
"abc" == "ab"
# False
"abc" == "abc"
# True
```

**Iterate each character in a string**

```python
word = 'test'
for c in word:
    print c

for i, c in enumerate(word):
    print i, c
```

**Convert all characters to uppercase/lowercase**

These make a new string with all letters converted to uppercase and lowercase, respectively.

```python
print string.upper()
# HELLO WORLD!
print string.lower()
# hello world!
```

**startswith/endswith**

This is used to determine whether the string starts with something or ends with something, respectively.

```python
print string.startswith("Hello")
# True
print string.startswith("hello")
# False
print string.endswith("!")
# True
```

**Split**

This splits the string into a bunch of strings grouped together in a list. If not specified, the default of string.split() is splitting by space.

```python
print string.split(" ")
# ['Hello', 'world!']
print string.split("l")
# ['He', '', 'o wor', 'd!']
```

**Enumerate**

The `enumerate()`function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.

```python
string = 'cold'
print list(enumerate(string))
# [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
```

**Join strings**

```python
print ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
# This will join all words into a string

print '#'.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
# This#will#join#all#words#into#a#string
```

**Length**

Length including punctuation and spaces.

```python
len(string)
# 12
```

**Count**

differentiate uppercase and lowercase

can count the number of space

can count the number of punctuation

```python
print string.count("l")
# 3
print string.count("h")
# 1
print string.count("H")
# 0 
print string.count(" ")
# 1
print string.count("!")
# 1
```

**Finding substring**

Both `index` and `find` return the index of the first occurrence of the first character in the substring. The only difference is that when the substring is not found, `index` returns `ValueError` and `find` returns `-1`.

```python
string = "hello world"

print string.index("l")
# 2
print string.index("ll")
# 2

print string.find("l")
# 2
print string.find("ll")
# 2

print string.index("lll")
# ValueError: substring not found

print string.find("lll")
# -1
```

**Replace part of a string**

When using replace() to replace part of a string, need to assign the new value to the original name. Because string is immutable. Otherwise, the string won't be changed.

```python
string = "hello world"
string = string.replace("hello", "Hello")
print string
# Hello world
```

**Check if a string is letter**

`str.isalpha()`Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

```python
string = 'abc'
print string.isalpha()
# True
```

## A list of build-in functions for strings

| Method                                                                                                   | Description                                        |
| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| [Python String capitalize()](https://www.programiz.com/python-programming/methods/string/capitalize)     | Converts first character to Capital Letter         |
| [Python String center()](https://www.programiz.com/python-programming/methods/string/center)             | Pads string with specified character               |
| [Python String casefold()](https://www.programiz.com/python-programming/methods/string/casefold)         | converts to casefolded strings                     |
| [Python String count()](https://www.programiz.com/python-programming/methods/string/count)               | returns occurrences of substring in string         |
| [Python String endswith()](https://www.programiz.com/python-programming/methods/string/endswith)         | Checks if String Ends with the Specified Suffix    |
| [Python String expandtabs()](https://www.programiz.com/python-programming/methods/string/expandtabs)     | Replaces Tab character With Spaces                 |
| [Python String encode()](https://www.programiz.com/python-programming/methods/string/encode)             | returns encoded string of given string             |
| [Python String find()](https://www.programiz.com/python-programming/methods/string/find)                 | Returns the Highest Index of Substring             |
| [Python String format()](https://www.programiz.com/python-programming/methods/string/format)             | formats string into nicer output                   |
| [Python String index()](https://www.programiz.com/python-programming/methods/string/index)               | Returns Index of Substring                         |
| [Python String isalnum()](https://www.programiz.com/python-programming/methods/string/isalnum)           | Checks Alphanumeric Character                      |
| [Python String isalpha()](https://www.programiz.com/python-programming/methods/string/isalpha)           | Checks if All Characters are Alphabets             |
| [Python String isdecimal()](https://www.programiz.com/python-programming/methods/string/isdecimal)       | Checks Decimal Characters                          |
| [Python String isdigit()](https://www.programiz.com/python-programming/methods/string/isdigit)           | Checks Digit Characters                            |
| [Python String isidentifier()](https://www.programiz.com/python-programming/methods/string/isidentifier) | Checks for Valid Identifier                        |
| [Python String islower()](https://www.programiz.com/python-programming/methods/string/islower)           | Checks if all Alphabets in a String are Lowercase  |
| [Python String isnumeric()](https://www.programiz.com/python-programming/methods/string/isnumeric)       | Checks Numeric Characters                          |
| [Python String isprintable()](https://www.programiz.com/python-programming/methods/string/isprintable)   | Checks Printable Character                         |
| [Python String isspace()](https://www.programiz.com/python-programming/methods/string/isspace)           | Checks Whitespace Characters                       |
| [Python String istitle()](https://www.programiz.com/python-programming/methods/string/istitle)           | Checks for Titlecased String                       |
| [Python String isupper()](https://www.programiz.com/python-programming/methods/string/isupper)           | returns if all characters are uppercase characters |
| [Python String join()](https://www.programiz.com/python-programming/methods/string/join)                 | Returns a Concatenated String                      |
| [Python String ljust()](https://www.programiz.com/python-programming/methods/string/ljust)               | returns left-justified string of given width       |
| [Python String rjust()](https://www.programiz.com/python-programming/methods/string/rjust)               | returns right-justified string of given width      |
| [Python String lower()](https://www.programiz.com/python-programming/methods/string/lower)               | returns lowercased string                          |
| [Python String upper()](https://www.programiz.com/python-programming/methods/string/upper)               | returns uppercased string                          |
| [Python String swapcase()](https://www.programiz.com/python-programming/methods/string/swapcase)         | swap uppercase characters to lowercase; vice versa |
| [Python String lstrip()](https://www.programiz.com/python-programming/methods/string/lstrip)             | Removes Leading Characters                         |
| [Python String rstrip()](https://www.programiz.com/python-programming/methods/string/rstrip)             | Removes Trailing Characters                        |
| [Python String strip()](https://www.programiz.com/python-programming/methods/string/strip)               | Removes Both Leading and Trailing Characters       |
| [Python String partition()](https://www.programiz.com/python-programming/methods/string/partition)       | Returns a Tuple                                    |
| [Python String maketrans()](https://www.programiz.com/python-programming/methods/string/maketrans)       | returns a translation table                        |
| [Python String rpartition()](https://www.programiz.com/python-programming/methods/string/rpartition)     | Returns a Tuple                                    |
| [Python String translate()](https://www.programiz.com/python-programming/methods/string/translate)       | returns mapped charactered string                  |
| [Python String replace()](https://www.programiz.com/python-programming/methods/string/replace)           | Replaces Substring Inside                          |
| [Python String rfind()](https://www.programiz.com/python-programming/methods/string/rfind)               | Returns the Highest Index of Substring             |
| [Python String rindex()](https://www.programiz.com/python-programming/methods/string/rindex)             | Returns Highest Index of Substring                 |
| [Python String split()](https://www.programiz.com/python-programming/methods/string/split)               | Splits String from Left                            |
| [Python String rsplit()](https://www.programiz.com/python-programming/methods/string/rsplit)             | Splits String From Right                           |
| [Python String splitlines()](https://www.programiz.com/python-programming/methods/string/splitlines)     | Splits String at Line Boundaries                   |
| [Python String startswith()](https://www.programiz.com/python-programming/methods/string/startswith)     | Checks if String Starts with the Specified String  |
| [Python String title()](https://www.programiz.com/python-programming/methods/string/title)               | Returns a Title Cased String                       |
| [Python String zfill()](https://www.programiz.com/python-programming/methods/string/zfill)               | Returns a Copy of The String Padded With Zeros     |
| [Python String format\_map()](https://www.programiz.com/python-programming/methods/string/format_map)    | Formats the String Using Dictionary                |
| [Python any()](https://www.programiz.com/python-programming/methods/built-in/any)                        | Checks if any Element of an Iterable is True       |
| [Python all()](https://www.programiz.com/python-programming/methods/built-in/all)                        | returns true when all elements in iterable is true |
| [Python ascii()](https://www.programiz.com/python-programming/methods/built-in/ascii)                    | Returns String Containing Printable Representation |
| [Python bool()](https://www.programiz.com/python-programming/methods/built-in/bool)                      | Coverts a Value to Boolean                         |
| [Python bytearray()](https://www.programiz.com/python-programming/methods/built-in/bytearray)            | returns array of given byte size                   |
| [Python bytes()](https://www.programiz.com/python-programming/methods/built-in/bytes)                    | returns immutable bytes object                     |
| [Python compile()](https://www.programiz.com/python-programming/methods/built-in/compile)                | Returns a Python code object                       |
| [Python complex()](https://www.programiz.com/python-programming/methods/built-in/complex)                | Creates a Complex Number                           |
| [Python enumerate()](https://www.programiz.com/python-programming/methods/built-in/enumerate)            | Returns an Enumerate Object                        |
| [Python filter()](https://www.programiz.com/python-programming/methods/built-in/filter)                  | constructs iterator from elements which are true   |
| [Python float()](https://www.programiz.com/python-programming/methods/built-in/float)                    | returns floating point number from number, string  |
| [Python input()](https://www.programiz.com/python-programming/methods/built-in/input)                    | reads and returns a line of string                 |
| [Python int()](https://www.programiz.com/python-programming/methods/built-in/int)                        | returns integer from a number or string            |
| [Python iter()](https://www.programiz.com/python-programming/methods/built-in/iter)                      | returns iterator for an object                     |
| [Python len()](https://www.programiz.com/python-programming/methods/built-in/len)                        | Returns Length of an Object                        |
| [Python max()](https://www.programiz.com/python-programming/methods/built-in/max)                        | returns largest element                            |
| [Python min()](https://www.programiz.com/python-programming/methods/built-in/min)                        | returns smallest element                           |
| [Python map()](https://www.programiz.com/python-programming/methods/built-in/map)                        | Applies Function and Returns a List                |
| [Python ord()](https://www.programiz.com/python-programming/methods/built-in/ord)                        | returns Unicode code point for Unicode character   |
| [Python reversed()](https://www.programiz.com/python-programming/methods/built-in/reversed)              | returns reversed iterator of a sequence            |
| [Python slice()](https://www.programiz.com/python-programming/methods/built-in/slice)                    | creates a slice object specified by range()        |
| [Python sorted()](https://www.programiz.com/python-programming/methods/built-in/sorted)                  | returns sorted list from a given iterable          |
| [Python sum()](https://www.programiz.com/python-programming/methods/built-in/sum)                        | Add items of an Iterable                           |
| [Python zip()](https://www.programiz.com/python-programming/methods/built-in/zip)                        | Returns an Iterator of Tuples                      |
