ALL 47 STRING METHODS IN PYTHON EXPLAINED
Summary
TLDRThis video script offers an extensive tutorial on Python's string methods, covering a total of 47 functions excluding dunder methods. It begins with common methods like 'capitalize' and 'upper', then delves into lesser-known functionalities. Each method is explained with examples, from simple case manipulations to complex string encoding and pattern searches. The script also clarifies the differences between methods that may seem similar, such as 'isdecimal', 'isdigit', and 'isnumeric'. The tutorial is rounded off with methods for string formatting, partitioning, and justification, providing a comprehensive guide for anyone looking to master string manipulation in Python.
Takeaways
- 📝 The lesson covers 47 string methods in Python, excluding the dunder methods, providing a comprehensive overview of string manipulation capabilities.
- 🔄 'capitalize' and 'casefold' methods are used to transform strings to start with a capital letter and to enable caseless comparisons, respectively.
- 📏 'center' allows for centering a string within a given width, optionally padded with a specific character.
- 🔢 'count' is utilized to determine the number of occurrences of a substring within a string.
- 🔠 'encode' converts a string into a byte representation, with options to handle encoding errors.
- 🔚 'endswith' checks if a string concludes with a specified character or tuple of characters.
- 📖 'expandtabs' is used to convert tab characters into spaces, based on a defined tab width.
- 🔍 'find' and 'index' locate the position of a substring within a string, with 'index' raising an error if the substring is not found.
- 📐 'format' and 'format_map' offer ways to insert values into a string with placeholders and dictionary mappings, respectively.
- 🔤 'isalnum', 'isalpha', 'isdigit', 'isdecimal', and 'isnumeric' are used to check for strings containing specific types of characters, with 'isalnum' being the broadest check.
- 🛑 'index' is a method that, unlike 'find', will throw an error if the specified substring is not present in the string.
- 🔗 'join' is used to concatenate elements of an iterable with a specified string as a separator.
- 🔄 'lower' and 'upper' convert strings to lowercase and uppercase, respectively, while 'swapcase' swaps the case of each character.
Q & A
What does the 'capitalize' method do in Python?
-The 'capitalize' method converts the first character of a string to uppercase and the rest to lowercase.
How does the 'casefold' method help in string comparison?
-The 'casefold' method returns a case-insensitive version of the string, which helps in comparing strings without worrying about case differences.
What is the purpose of the 'center' method?
-The 'center' method centers the string in a field of a specified width, optionally filling the surrounding space with a specified character.
How does the 'count' method work?
-The 'count' method returns the number of non-overlapping occurrences of a substring in the string.
What is the function of the 'encode' method?
-The 'encode' method encodes the string using the specified encoding and returns the encoded bytes object.
How can you check if a string ends with a specific suffix using Python?
-You can use the 'endswith' method to check if a string ends with a specified suffix or any of a tuple of suffixes.
What does the 'expandtabs' method do?
-The 'expandtabs' method replaces tabs in the string with spaces, using a specified tab size.
How do the 'find' and 'index' methods differ?
-Both methods return the lowest index of the substring if found, but 'find' returns -1 if the substring is not found, while 'index' raises a ValueError.
What is the use of the 'format' and 'format_map' methods?
-The 'format' method allows you to format strings using placeholders, while 'format_map' formats strings using a dictionary for the placeholders.
How do the 'isdecimal', 'isdigit', and 'isnumeric' methods differ?
-The 'isdecimal' method checks if all characters are decimal characters, 'isdigit' checks if all characters are digits, and 'isnumeric' checks if all characters are numeric, including digits, decimals, and other numeric characters.
Outlines
📘 Introduction to Python String Methods
This paragraph introduces a comprehensive tutorial on Python's string methods. The speaker outlines the plan to cover all 47 string methods, excluding dunder methods, to ensure a complete understanding of string manipulation in Python. The 'capitalize' and 'casefold' methods are demonstrated with examples, showing how they can be used to manage case in strings. The 'center' method is also explained, illustrating how to center-align text within a specified width.
🔍 Exploring More String Methods in Python
Continuing from the introduction, this paragraph delves deeper into various string methods. The 'count' method is showcased for counting substring occurrences, while the 'encode' method is used to encode strings into bytes, with an optional error handling parameter. The 'endswith' method checks for ending characters or tuples of characters, and 'expandtabs' is used to convert tabs into spaces. The 'find' method locates the first occurrence of a substring, and 'format' is introduced for string formatting, both with named placeholders and without.
📚 Advanced String Method Applications in Python
The script now focuses on more advanced string methods. It explains the use of 'format_map' for dictionary-based string formatting, 'index' for finding the position of a substring with error-raising if not found, and 'isalnum', 'isalpha', 'isascii', and 'isdigit' for checking alphanumeric, alphabetic, ASCII, and digit-only strings. The paragraph also clarifies the differences between 'isdecimal', 'isdigit', and 'isnumeric', emphasizing their specific use cases.
🔑 Python String Methods for Validation and Transformation
This paragraph covers methods for validating and transforming strings. 'isidentifier' checks for valid Python identifier names, while 'lower' and 'upper' methods are used for case conversion. 'join' is introduced for concatenating elements of an iterable with a specified separator. 'ljust' and 'rjust' are explained for left and right text justification, and 'lower' is revisited for converting uppercase strings to lowercase. 'lstrip' and 'rstrip' methods are demonstrated for stripping characters from the left and right sides of a string.
🛠️ Additional String Manipulation Techniques in Python
The script continues with more string manipulation methods. 'maketrans' and 'translate' are paired for creating translation tables and applying them to strings. 'partition' and 'rpartition' are used for splitting strings based on a separator, with 'rpartition' starting from the right. 'removeprefix' and 'removesuffix' methods are introduced for removing specified prefixes or suffixes from strings. The paragraph also explains 'replace' for substituting substrings within a string and provides an example of limiting the number of replacements.
🔄 Reversing, Splitting, and Stripping Strings in Python
This paragraph discusses methods for reversing, splitting, and stripping strings. 'rfind' and 'rindex' are used for finding the last occurrence of a substring from the right, with 'rindex' raising an error if the substring is not found. 'rjust' and 'ljust' are revisited for justifying text within a given width. 'rpartition' and 'partition' are contrasted, with 'rpartition' focusing on the right side of the string. 'rsplit' and 'split' are introduced for splitting strings from the right and left, respectively, with 'maxsplit' controlling the maximum number of splits.
📖 Wrapping Up Python String Methods with Practical Examples
The final paragraph wraps up the tutorial with additional string methods. 'rstrip' is used for stripping characters from the right side of a string. 'splitlines' is introduced for splitting a string into lines based on newline characters, with an option to keep the newline characters. 'startswith' checks if a string starts with a specified substring. 'strip' is showcased for removing specified characters from both sides of a string. 'swapcase' is used for swapping the case of characters in a string. The 'title' method is highlighted for creating title-cased strings, and 'upper' is revisited for converting strings to uppercase. The tutorial concludes with 'zfill' for padding strings with zeros.
Mindmap
Keywords
💡String Methods
💡Capitalize
💡Case Fold
💡Center
💡Count
💡Encode
💡EndsWith
💡Expand Tabs
💡Find
💡Format
💡Join
Highlights
Introduction to 47 string methods in Python, excluding dunder methods.
The 'capitalize' method to transform the first letter of a string to uppercase.
Using 'casefold' for caseless string comparisons.
'center' method to center-align strings with a specified width and fill character.
The 'count' method to find the number of occurrences of a substring.
'encode' method to convert strings into bytes using character encoding.
The 'endswith' method to check if a string ends with a specific character or tuple of characters.
'expandtabs' to convert tab characters to spaces with a defined tab width.
Using 'find' to locate the position of a substring within a string.
The 'format' method for string interpolation with keywords and arguments.
'format_map' to substitute formatted fields in a string using a dictionary.
'index' method to find the position of a substring, with error handling if not found.
The 'isalnum' method to check if a string contains only alphanumeric characters.
'isalpha' to verify if a string is composed solely of alphabetic characters.
'isascii' to determine if a string contains only ASCII characters.
The 'isdigit' method to check for a string that consists entirely of digits.
'isdecimal' to ascertain if a string represents a decimal number.
'isidentifier' to validate if a string is a valid Python identifier.
'islower' to check if all characters in a string are lowercase.
The 'isprintable' method to determine if a string contains only printable characters.
'isspace' to verify if a string contains only whitespace characters.
'istitle' to check if a string follows title capitalization rules.
'isupper' to determine if all characters in a string are uppercase.
The 'join' method to concatenate elements of an iterable with a specified separator.
'ljust' to left-align and pad a string to a given width with a fill character.
'lower' to convert all characters in a string to lowercase.
'lstrip' to remove leading characters or whitespace from the left side of a string.
Using 'maketrans' and 'translate' for creating translation tables and applying them.
'partition' to split a string into a tuple at the first occurrence of a separator.
'removeprefix' to eliminate a specified prefix from the beginning of a string.
'removesuffix' to remove a specified suffix from the end of a string.
'replace' to substitute occurrences of a substring with another substring.
The 'rfind' method to locate the last occurrence of a substring from the right.
'rindex' to find the last occurrence of a substring from the right with error handling.
'rjust' to right-align and pad a string to a given width with a fill character.
'rpartition' to split a string into a tuple at the last occurrence of a separator.
'rstrip' to remove trailing characters or whitespace from the right side of a string.
'splitlines' to split a string into a list of lines, with optional preservation of line endings.
'startswith' to check if a string starts with a specified prefix.
'strip' to remove leading and trailing characters or whitespace from both sides of a string.
'swapcase' to invert the case of each character in a string.
'title' to capitalize the first letter of each word in a string.
'upper' to convert all characters in a string to uppercase.
'zfill' to pad a numeric string with zeros on the left to fill a specified width.
Transcripts
in today's lesson we're going to be
going over all of the string Methods
that come with the string in Python so I
mean there's a lot of common ones such
as split or upper that you are probably
familiar with but there are also a lot
that aren't really that commonly used
and I want to just cover every single
one of these so there are going to be 47
in total excluding the dunder methods so
in case you're curious about everything
you can do with a string follow along
with this video because we're going to
be covering 47 of these string Methods
for number one we have capitalize which
means if we have some text and that's in
lowercase or uppercase we can capitalize
that and
when we run this we're going to get
hello with a capital H and if this is in
uppercase it's still going to capitalize
that string next we have case fold which
returns a version of the string for
caseless comparisons so pretend you have
Mario here that's spelled a bit weird if
we run this it's going to make sure that
we can compare this to another Mario
without having to worry about whether
this is uppercase or lowercase so if we
duplicate this line and say text 2 and
change this to Mario
like that as you probably know this is
not going to be equal to this because of
the case sensitivity but if we print
both of them text 1 and text two they're
both going to be processed into a
version that can be compared without
having to worry about the case next we
have the center method so suppose we
have some text and we want to call Dot
Center on it provide some sort of number
and that number is going to specify how
many characters you want this string to
occupy and where you want the text to be
centered and optionally you can include
a character or a string that's going to
be placed around the string that you
want to Center number four is Count
suppose you have a string with some sort
of substring that you want to count here
if we type in ABC underscore ABC
underscore ABC and so on and then we use
the method dot count with only a b we're
going to get a return of 4 because it's
counting all the occurrences of a b in
this string for number five we have
encode which allows us to encode a
string of our choice and if we run this
we're going to get the byte version of
Elon Musk because we were able to encode
that into utf-8 and you can also provide
an optional parameter which says errors
and if you set this to strict it means
that if it cannot encode it it's going
to throw an error which is good in case
you want to make sure that this does
become encoded for number six we have
the ends with method which checks that a
string ends with a certain letter such
as e if we check now that Apple ends
with e we're going to get a return of
true and this doesn't have to be a
single character it can actually be a
tuple of characters such as e and we can
also say a so now it's going to check
that it ends with either e or a and if
we run that we're still going to get
true and if we type in apla it will
still be true but if we type in
something such as Zed it's going to
return false because neither e nor a was
at the end of our string number seven
expand tabs right here we have a string
with some tabs as you can see by the
backslash T using dot expand tabs allows
us to expand those tabs using spaces so
here I defined a value of 20 which means
when we run this you'll see that we'll
get some very long tabs inside our
string number eight find
suppose we have a string that says
something silly such as remember to
comment and subscribe and suppose we
want to find the substring of subscribe
in this string well we can do that using
the text Dot find method and it's going
to return to us the integer of the first
and lowest occurrence of subscribe so if
we have multiple subscribes it's going
to return the first one that it finds
now if we run this we're going to find
that subscribe was located at the index
of 24 so I went ahead and printed
everything after that position and that
returned to me subscribe
now if we don't have what we are looking
for such as as does it's going to return
to us the index of negative one number
nine format here are two different ways
we can use this method with strings the
first way is defining some keywords
inside the string followed by some curly
brackets and then typing in text.format
followed by the keyword arguments such
as
subject and action which I've included
in this string now subject is going to
be replaced by cat and action is going
to be replaced by meow and the same
thing works without having to specify
the keywords now when we run both of
these it's going to say cat is doing
meow next we have format map which Maps
a dictionary to the formatted values
that we have in our string so for
example if we have a dictionary with X
and Y and then we have a string using
those values we can just call text Dot
format map coordinates and it's going to
place these values in the given values
down here so if we run this we'll get
that the coordinates are 10 and -5
number 11 Index right here we have a
string that says astronauts recently
discovered a banana on the moon question
mark and we want to find the position of
banana now recently I showed you that we
can use find to find the position of a
certain substring and we can achieve the
same thing with index except index does
have one difference and that is that if
we do not find what we're looking for
it's going to throw an error instead of
returning to us minus one number 12
is al-num which stands for is
alphanumeric and that checks that the
string contains letters or numbers but
if it contains something such as an
exclamation mark or some other symbol
it's not going to be considered
alphanumeric anymore so right now if we
run this with hello kitty123 it is
alphanumeric because it only contains
letters and numbers but if we add an
exclamation mark for example it's going
to evaluate two false because an
exclamation mark is neither a number nor
a letter number 13 is Alpha and that
checks that the text is alphabetic only
so if we run this it's going to return
false because Hello Kitty contains
numbers but if we remove the numbers
it's going to evaluate to True number 14
is Ashi and that returns to us true if
the current string contains only ashy
characters so if we decide to add these
symbols such as a copyright Mark to our
text it's going to return false to us
because that is not part of the Ashi
table but if we exclude that it's going
to return true to us now for 15 16 and
17 I decided to bring in my notes for
this because these are quite confusing
if you don't have them side by side so
what we're covering now is is decimal is
digit and is numeric so right now if you
want to make sure that something is
actually a number you can use is decimal
and that's going to evaluate one two
three to true and if you run that the
first one is going to evaluate to true
but if we decide to evaluate something
that is numeric but not a decimal such
as these crazy symbols here it's going
to evaluate to false and that is because
it is only checking that this is a
decimal now is digit checks for
something very similar it checks that
the current string is a digit and one
two three four five six even in these
crazy bubbles is considered a digit so
it's going to evaluate to true
now numeric on the other hand is going
to just evaluate the true if the number
happens to be numeric so all these
Japanese numbers do evaluate the numbers
so it's considered numeric but this does
not work if you put it inside here
because it is not a digit
now the reason I brought all three of
these together is just to show you that
they actually work in quite similar ways
and that is that is numeric works with
all three is digit works with these two
and is decimal only works with numbers
so what I'm trying to say is that if you
wanted to include some numbers inside is
numeric such as one two three it will
still evaluate to true
if you wanted to include some crazy
symbols like these ones that are digits
it will still evaluate to true
but this does not work the other way
around so if we take these Japanese
numbers and place them inside the is
digit it's going to evaluate two false
because it is not a digit even though it
is numeric but for the most part of the
time you probably just want to check
that it is a decimal so I would
recommend using that but in case you
want to check whether something is
numeric or is a digit you also have that
option
number 18 is identifier
here we have some text that says test
sample and what this does is check that
it is a valid identifier name in Python
in case you want to use it to name a
variable for example if we run this
we're going to get false because you
cannot use dashes in names in Python if
we change it to an underscore it will
work but if we change this to a one test
underscore sample it will still return
false because numbers cannot proceed
variable names in Python number 19 is
lower here we have some text with ABC
with a uppercased and what this does is
check that the entire string is
lowercased if we run this we're going to
get false as a return because ABC has a
capital A but if we return it with a
lowercase it's going to evaluate to True
number 20 is printable all this does is
check that the current line of text is
actually printable and it considers text
to be printable if it doesn't contain
any Escape characters such as new line
if we run this right now we're going to
get false because it contains this
escape sequence but if we return it
without that escape sequence we're going
to get true as a return number 21 is
space all this does is check that a
string only contains space so if we
create this string with a lot of empty
space and run the program we're going to
get true as a return because it is only
space
number 22 is title is title checks that
the given string is a title so that
video is going to elaborate to true
because it is a title it follows the
title syntax if we type in something
such as hello video it's going to
evaluate the false because hello is not
uppercased so all it's really doing is
checking that that the first letter of
each word is uppercased number 23 is
upper here we have a string with bananas
in complete uppercase and all this does
is check that the entire string is
uppercased here we're going to get a
return of true because bananas is
uppercased but if we add a lowercase n
it's going to evaluate the false because
it is not entirely uppercased number 24
join right now we have a text of type
string and we want to combine some words
for example so what join does is combine
an array of items together using the
given string so this is going to be
placed in between each one of the
elements that we are joining and to call
it we just have to say text Dot join and
we're going to join an array of our
choice so if we run this we'll get text
1 dash text 2-text3 and you will
probably see it without this because it
is an extra line of code that you don't
need and used instead like this with a
dash and with that we will still get the
same result but without having to use
this extra variable next we have L just
which aligns the text as far as possible
to the left with the amount of space
that we've provided so here we have
text.eljust and I decided to give it 20
characters of space and to fill the
remaining with the underscore so if we
run this we're going to get text and
underscore field for the remaining spots
inside this string number 26 lower right
now we have a string that has been
uppercased and all we want to do is
convert it to lowercase and we can use
that using text Dot lower so uppercase
in uppercase is going to become an
uppercase in lowercase number 27 L strip
here we have some text and pretend you
want to remove some from some text we
can do that using dot L strip followed
by the keyword or the text that you want
to remove from the left side of the
string so if we remove that we will just
have text remaining and if we do sum
with some space it's also going to
remove the space in front of text number
28 and 29
make trans and translate these two tend
to go hand in hand when you are working
with them because what make trans does
is create a translation table so right
now what we're saying is that we want to
convert this text to a translation table
and to do that we want to make sure that
every uppercase b gets translated to
this Emoji over here and then we want to
use that translation table for the text
that we want to print because right now
if we print this text as it is even if
we've created a table it's not going to
do anything but if we translate it with
the table that we've created here it's
going to replace each uppercase B with
this emoji
and if we run that we'll see that 66 or
that character was replaced with this
emoji character and that's why we're
going to get this funky string over here
and the cool thing about that is that
you can use any new string you want it
can even be that is bacon
baby
and when you run this we're going to get
each one of the uppercase B's replaced
with this symbol over here if you want
to have more than just one character
converted you can enter your own
dictionary key and it's going to create
a translation table number 30 partition
suppose you have a string such as a plus
b equals c and you want to partition
these in other words split them at a
certain point you can use the dot
partition method to make sure that you
split this into three equal strings at
the index of equal and what that really
means is that we're using equals as a
separator to tell the program that we
want to split this string into three
parts between the equal sign so we're
going to get back a plus b equals and C
number 31 remove prefix here we have a
string that says
and what we want to do is remove the
beginning part which says was to do that
we just type in dot remove prefix and
all we're going to get back is app now
for number 32 it's exactly the opposite
we are removing the suffix so here we
have Mr everyone and we want to remove
one from this so here we'll just type in
text Dot remove suffix with one and when
we run that we'll get Mr every now
number 33 is one of the most important
ones because it tells you to remember to
comment I'm just joking about that of
course but here we have a string that
says remember to comment and all we're
going to do is replace it with subscribe
so here you can choose a substring that
you want to replace and replace it with
the current string that you've provided
so if we run that instead of saying
remember to comment it's going to say
remember to subscribe and optionally in
case you have many occurrences of the
same word you can provide a limit to how
many times you want to replace that text
so instead of replacing every occurrence
of comment with subscribe we're only
going to replace the first occurrence so
now it's going to say remember to
subscribe and to comment
number 34 are find here we have some
text that says a some text Dot a and
what we want to do is find the first
occurrence of a starting from the right
so here if we type in text Dot our find
and we print the position we're going to
get the latter and not the first if we
use the original we're going to get the
first one
and just as before if you type in
something that doesn't exist you're
going to get -1 when you use find when
you use index you're going to get an
error
but what better way to explain that than
using the exact same example except with
our index which does the same thing as
index except it starts from the end and
searches in this direction so if we look
for B it's going to return to us 14
because it's starting from the right
side and again if you type in something
that doesn't exist it's going to give us
a value error number 36 are justify here
we have some text and we're just going
to say text dots are just and we want to
make sure that this string occupies 20
spaces and we're going to fill the
remaining with the underscore and as you
can see in the output that's what R just
does now at this point you know what
partition does it splits the string into
three depending on the separator that
you've defined but we also have
something called R petition which tells
us which tells the program to start from
the right side so instead of getting
text and having this as a divider we're
going to be using the second one instead
because it use because it starts from
the right side and if we run that you'll
see text equals text 2 equals but if we
remove the r from our partition it's
going to do it the opposite way
38 and 39 are splits and split but first
we're going to cover our split
so here we have some text that says this
is some special stuff and what our split
does is starting from the right it
splits the string into an array given
the separator that we've provided
so as you can see here we have some
space that we decided to use as a
separator so it's going to split each
and every one of these words into its
own element and if we run that we'll get
this is some special stuff because we
used the space as a separator
and the same thing goes for this website
over here we decided to use a DOT as a
separator so it's separated w w website
and com
now text.split is the exact same thing
except it evaluates this from the left
side so it starts splitting in this
direction which means that if we run
this program right now and provide a Max
split of two it's going to split this
two times at most so this is some
special stuff as you can see it
separated these two but it did not
separate the rest because we said we're
only going to separate the first two
elements and the reason I used Max split
here is because I wanted to show you
that if we use R split with Max split
it's going to do it in the opposite
direction because it starts from the
right side first next we have R strip
which strips the text from the right
side so here we have text.r strip and we
want to strip Mario from the right side
and since we have two Marios here it's
going to remove this Mario right there
and now we'll have an output of his name
is Mario 41 we have split lines so
suppose you have some text and the text
has some separators such as slash n
which starts a new line text Dot split
lines is going to take each one of those
lines and put it as an element into an
array so if we run this we'll get
remember to comment as two different
elements in an array
now you can specify this parameter keep
ends to be true or false depending on
whether you want to keep these escaped
characters without it you're just going
to get D strings without the backslash n
included in both of the elements number
42 starts with suppose you have a string
that starts with L you can check that by
using the dot starts with
method and it's going to check that
Luigi starts with L which is true but
Luigi does not start with f and that can
be proven by using this method number 43
strip suppose you want to remove Luigi
from this string you can just type in
text Dot strip and here we're just
removing Luigi by inserting Luigi so by
running this we will effectively remove
Luigi and this one works for both sides
so you can either remove pasta or Luigi
depending on your preference as you can
see if we type in past that dot it will
also remove pasta number 44 swap case
here we have a string that says Luigi
has pasta and let's just swap case that
the easiest way to explain this is to
run it now we have Luigi has pasta in a
swap case
now one that's really interesting in
Python that can help you a lot in case
you don't know how to write a title is
the dot title method here I wrote
something that's called This is a title
and what this is a title do is make sure
that each letter is uppercased in your
title so I would say simple way to make
a title and I think this is one of my
favorite string Methods because of it
number 46 upper here we have some text
that says hello there and we just want
to uppercase that and if we run this
we'll get hello there in screaming
characters and finally we have number 47
which is also the final method that we
will be covering in this video and that
is zero fill so right now we have some
text and if we just run this as it is
you'll see that text is going to be
filled with some zeros just in case you
have to add some zeros to your text but
anyways those were 47 string Methods
that you can use in Python do let me
know in the comment section down below
if you learned something new or if there
was something that I missed regarding
these methods this video took me 50
minutes to record and it's actually even
growing longer because of this
explanation but if you did enjoy the
video do consider leaving a like and a
comment I love to read those but
otherwise with that being said I also
want to wish all of you a Happy New Year
I know this is quite late maybe it's day
five day six of the year but this is the
first video I'm recording this year so I
thought I might as well mention it
otherwise with that being said as always
thanks for watching and I'll see you in
the next video
oh
Посмотреть больше похожих видео
5.0 / 5 (0 votes)