Strings and their Methods in Python 3.9 🐍
Tags: python, codenewbie, computerscience
Published: 2020-11-02 20:52:29

> A bit on what strings are and their METHODS (which make life easier) !! 🔥🔥🔥

**NOTE:**

1. Almost all of the content in this article is taken from the official **Python Docs**, and divided into digestible chunks so that people like me can understand it (little by little).

2. This article is pretty straight forward. I tried to make it as crisp as possible.

3. It's more code and less talk cause:

![Talk is Cheap, Show me the code - Linus Torvalds](https://dev-to-uploads.s3.amazonaws.com/i/p18xanr8kpzn6b7zno5n.jpg)

### Let's get started! 🐍🔥

# **What are Strings?**
## In Short:
Strings are a sequence of characters, used for storing Textual Data.

### Examples ✨:

```python

'Hello, World!' # single quotes

"This is an example(!) of a String" # double quotes

"Single 'quote' embedded in double quotes and vice versa is allowed"

'''Three single quotes and double are allowed! You can also embed 'single quotes' and "double quotes" just the way I did in this example.'''
```

#### Also,

They are **Immutable** i.e. **They can't be modified, just like JavaScript 🔥**.

# **Some Very Common and Useful String (str) Methods with examples:**

### ⭐ capitalize, center (with docs)

![capitalize, center](https://dev-to-uploads.s3.amazonaws.com/i/ugay2385zgs1qvk5q8ev.png)

### ⭐ count, encode (with docs)

![count, encode](https://dev-to-uploads.s3.amazonaws.com/i/0hqp16qjb4hbwcw3qa03.png)
 
### ⭐ endswith, expandtabs (with docs)

![endswith, expandtabs](https://dev-to-uploads.s3.amazonaws.com/i/e0xrl3rt9jywotxzsb3t.png)

### ⭐ find, format (with docs)

![find, format](https://dev-to-uploads.s3.amazonaws.com/i/1tekjo6k0eav6efrjmn5.png)

### ⭐ index, isalnum, isalpha, isdigit, islower, isupper, isprintable, isspace, istitle (with (simplified) docs)

![more methods](https://dev-to-uploads.s3.amazonaws.com/i/n9e1c324jorouqjrsawv.png)

### ⭐ join, ljust, lower, upper, rjust, lstrip, rstrip, strip, partition, removeprefix and removesuffix (**Python 3.9**), replace, split, startswith, swapcase, title, upper

```python
# Common String (str) Methods in Python 3.9
# Note: Output is without quotes in prefix and suffix
 
s = "hello, world!"
 
# str.join(iterable): 
# Return a string which is the concatenation of the strings in iterable.
print(" ".join(["hello", "world", "!"])) # 'hello world !'
 
# str.ljust(width[, fillchar]): (Remember "center" method?)  Return the string left justified in a string of length width.
# Padding is done using the specified fillchar (default is an ASCII space).
print(s.ljust(20, "-")) # 'hello, world!-------'
 
# str.rjust(width[, fillchar]): same as ljust except it returns right justified string
print(s.rjust(20, "-")) # '-------hello, world!'
 
print(s.upper()) # HELLO, WORLD! (Returns All Characters Upper-cased)
print(s.lower()) # hello, world! (Returns All Characters Lower-cased)
print(s.title()) # Hello, World! (Returns Titledcase String)
print(s.lstrip()) # hello, world! (Returns Copy of String with Leading Characters (default=whitespaces) removed)
print(s.rstrip('!')) # hello, world (Returns Copy of String with trailing Characters removed)
 
print('   hello, world! '.strip())
# hello, world (Returns Copy of String with trailing and leading Characters removed) (default=whitespaces)
 
print(s.partition(',')) # ('hello', ',', ' world!')
# Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator,
# the separator itself, and the part after the separator.
# If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
 
print(s.split('l')) # ['he', '', 'o, wor', 'd!'] # Return a list of the words in the string,
# using sep as the delimiter string.
 
print(s.replace('l', 'L')) # 'heLLo, worLd!'
# str.replace(old, new[, count]): Return a copy of the string with all occurrences of substring old replaced by new.
# If the optional argument count is given, only the first count occurrences are replaced.
 
# ===============
#   Python 3.9 ⭐
# ===============
 
print(s.removeprefix("hello, ")) # "world!"
# If the string starts with the prefix string, return string[len(prefix):].
# Otherwise, return a copy of the original string:
 
print(s.removesuffix(", world!")) # "hello"
# If the string ends with the suffix string and that suffix is not empty,
# return string[:-len(suffix)]. Otherwise, return a copy of the original string
```
# A little bit More ✨:
## f-strings

{% twitter 1293593885550112768 %}
 
# That's it! 🐍🔥

To Dig More into strings and stuff, [**click here**](https://docs.python.org/3/library/stdtypes.html) (where most of the content of this article is taken from).

**Thanks for reading. 🙏🏻**

*Feel free to leave a comment if you want to add up something or suggest what I should share next :)*