Strings and their Methods in Python 3.9 ๐Ÿ

Strings and their Methods in Python 3.9 ๐Ÿ

ยท

3 min read

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

Let's get started! ๐Ÿ๐Ÿ”ฅ

What are Strings?

In Short:

Strings are a sequence of characters, used for storing Textual Data.

Examples โœจ:


'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

โญ count, encode (with docs)

count, encode

โญ endswith, expandtabs (with docs)

endswith, expandtabs

โญ find, format (with docs)

find, format

โญ index, isalnum, isalpha, isdigit, islower, isupper, isprintable, isspace, istitle (with (simplified) docs)

more methods

โญ join, ljust, lower, upper, rjust, lstrip, rstrip, strip, partition, removeprefix and removesuffix (Python 3.9), replace, split, startswith, swapcase, title, upper

# 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

That's it! ๐Ÿ๐Ÿ”ฅ

To Dig More into strings and stuff, click here (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 :)