DEV Community

Cover image for Strings and their Methods in Python 3.9 🐍
Gagan Deep Singh
Gagan Deep Singh

Posted on • Updated on

Strings and their Methods in Python 3.9 🐍

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.'''
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

A little bit More ✨:

f-strings

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 :)

Top comments (4)

Collapse
 
tominekan profile image
Tomi Adenekan

How did you get your code to look like that?

Collapse
 
py_talk profile image
py.talk()

he's using carbon.now.sh/

Collapse
 
gagangulyani profile image
Gagan Deep Singh

I used Carbon.now.sh

Collapse
 
tominekan profile image
Tomi Adenekan

Ok, thanks.