python: common string functions

chapters

transformation functions
finding functions
checking functions

transformation functions

transformations functions doesn’t modify the current string since strings are imitable.Instead of,they return a copy.

remove leading and trailing whitespace:strip()

remove leading whitespace:lstrip()

remove trailing whitespace:rstrip()

split a string into a list of the words: split(sep: str, maxsplit: SupportsIndex ) .
sep : the delimiter character.by default that is whitespace.
maxsplit: Maximum number of splits to do. -1 (the default value) means no limit.
basic example:

token = 'I love animals'.split()
print(f'token={token}')

output:

token=['I', 'love', 'animals']

example where we limit the number of split:

token = 'www.fubar.google.com'.split('.', maxsplit=1)
print(f'token={token}')

output:

token=['www', 'fubar.google.com']

split a string into a list of the words: rsplit(sep: str, maxsplit: SupportsIndex ) .
contrary to the split() function this one starts at the end of the string and go on until the front but the order of the returned list is always the same.
so this function makes to be used with the maxsplit parameter.
example where it makes no sense to use it:

token = 'I love animals'.rsplit()
print(f'token={token}')

we can see that the result is the same as with the split() function:

token=['I', 'love', 'animals']

example where it makes sense to use it:

token = 'www.fubar.google.com'.rsplit('.', maxsplit=1)
print(f'token={token}')

output:

token=['www.fubar.google', 'com']

split a string into a list of strings breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true:
splitlines(self, keepends: bool = ...) -> list[str]
example:

token = 'Thank you my friend\nyou are the best\nDavid'.splitlines()
print(f'token={token}')

output:

    token=['Thank you my friend', 'you are the best', 'David']

join each element of an Iterable of strings (the parameter to pass to the method) with the current string: join(Iterable[str])
example:

join = '.'.join(['website', 'david', 'com'])
print(f'join={join}')

output:

join=website.david.com

replace all occurrences of substring old replaced by new : replace(__old: str, __new: str, __count: SupportsIndex )
optionally we can provide the count parameter to limit the number of replacement.
example:

replaced = 'i_love_chinchillas'.replace('_', ' ')
print(f'replaced={replaced}')

output:

replaced=i love chinchillas

return a lower case version of the string:
lower()

return a upper case version of the string:
upper()

return a capitalize version(first character in uppercase, the remaining in lowercase) of the string:
capitalize()

Return a formatted version of the string using substitutions from args and kwargs.
The substitutions are identified by braces ‘{‘ and ‘}’:
format(*args, **kwargs)
refer to the python basic page to get more details about this function.

remove the prefix if it is found otherwise return the original string:removeprefix()

remove the suffix if it is found otherwise return the original string:removesuffix()

finding functions

count the number of occurrence (non-overlapping)of the x parameter:
count(x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...)
example:

count = 'you are my friend and you are my baby'.count('my')
print(f'count={count}')

output:

count=2

Return the lowest index in the string where sub is found, such that sub is contained within S[start:end].
Optional arguments start and end are interpreted as in slice notation:
index() or find().
the complete signature is the same:
index(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...)
the difference between these 2 functions is that index() raises ValueError when the substring is not found while find() returns -1.
example:

index = 'you are my friend and you are my baby'.index('my')
print(f'index={index}')

output:

index=8

Return the highest index in the string where sub is found, such that sub is contained within S[start:end].
Optional arguments start and end are interpreted as in slice notation:
rindex() or rfind().
the complete signature is the same:
rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...)
the difference between these 2 functions is that rindex() raises ValueError when the substring is not found while rfind() returns -1.
example:

index = 'you are my friend and you are my baby'.rindex('my')
print(f'index={index}')

output:

index=30

checking functions

all these functions return a boolean value.

checking if as string represent a numeric value:
isdigit(), isnumeric(), isdecimal() allows to do this check.Their difference is quite subtil. so in the general case we can use anyone of them.

checking if the string is an alpha-numeric string(that is contains only number or alphabetical characters) :
isalnum()

checking if the string is an alphabetical string(that is contains only alphabetical characters) :
isalpha()

checking if the string doesn’t contain any uppercase characters :
islower()

checking if the string doesn’t contain any lowercase characters :
isupper()

example:

islower = 'ab_1-*.2ab'.islower()
print(f'islower={islower}')
 
isupper = 'AB_1-*.2AB'.isupper()
print(f'isupper={isupper}')

output:

islower=True
isupper=True
Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *