Saturday, May 28, 2022

String methods

We will cover some of the most commonly found methods -

str.capitalize(): Returns a copy of the string with only the first character capitalized and all others lowercase.

str.endswith(suffix[, start[, end]]): Returns True if the string ends with the specified suffix; otherwise, returns False. To look for multiple suffixes, a tuple can be used. The optional start is the index to start the search at, and the optional end is the ending index.

str.format(*args, **kwargs): Conducts a string formatting operation. This has been shown previously in other examples. There are many additional parameters that can be used with string formatting, so the official documentation should be referenced. On an additional note, the *args and **kwargs arguments are frequently found in the Python documentation. They simply indicate what types of arguments are accepted by a function or method. For *args, any argument passed in will be processed; **kwargs indicates key=value arguments are accepted. Naturally, if the argument passed in is not known, an error will be generated.

str.isalpha(): Returns True if all characters in the string are alphabetic. There are also methods for alphanumeric, numbers, ASCII-only, lowercase, and so on, checks.

str.ljust(width[, fillchar]): Returns a string that is left-justified with a length of width. By default, any extra space is padded with space characters, but fillchar can be used to provide alternative characters.

str.lower(): Returns a copy of the string that is all lowercase.

str.splitlines([keepends]): Returns a list of the individual lines within a string, as determined by common line separator characters.

The line breaks themselves are not included, unless keepends is True.

str.strip([chars]): Returns a copy of the string with the lead and trailing characters removed. By default, all whitespace is removed, but the optional chars argument can specify specific characters to remove.

str.title(): Returns a copy of the string in title case. Due to the algorithm used, apostrophe characters can cause problems with the expected output, so a review of the documentation is suggested prior to use.

As strings are simply specialized lists, they also have access to all the sequence methods listed in Sequence methods. Please note that these are not all the special methods available to strings.the full list can be found in the Python documentation.

Share:

0 comments:

Post a Comment