The 6th lesson of Python tutorial Strings Methods. - BoardCode

The 6th lesson of Python tutorial Strings Methods.

Share This

The 6th lesson of Python tutorial, strings methods.
In the last lesson we talked about strings, in this lesson we will continue speaking about them, especially their methods.

**Some of these methods have parameters and some don't. If a method takes parameters we'll mention that in parameters section.
**We will not adhere with the alphabetical order.
**In the parameters section we'll mention their types an if they are requireds or optionals. Directly under the parameters section we'll explain how does the method work.
** When we say:a method is like another method that means they take the same parametes but with a small difference in the work or in the result.
The methods.
str.capitalize():
returns a capitalized copy from str.
Example:
>>> "hello, world".capitalize()
'Hello, world'

>>> "hello, #world".capitalize()
Hello, #world'


str.lower():
returns a lowercased copy from str.
Examples:
>>> "PYTHON".lower()
'python'

>>> "dreß".lower()
'dreß'

>>> "PYTHON #?123".lower()
'python #?123'


str.islower():
True if all characters in str are in lowercase. Otherwise false.
Examples:
>>> "dreß".islower()
True

>>> "PYTHON #?123".islower()
False

>>> 'python #?123'.islower()
True


str.upper():
returns an uppercased copy of str.
Examples:
>>> "py thon".upper()
'PY THON'

>>> "py #?thon".upper()
'PY #?THON'


str.isupper()
True if all the characters were uppercased. Otherwise false. Examples:
>>> 'PY THON'.isupper()
True

>>> 'PY #?THON'.isupper()
True

>>> 'Py #?THON'.isupper()

False

str.swapcase():
swaps all lowercased letters in str to uppercase and the same with uppercased letters.
Examples:
>>> "hello, world".swapcase()
'HELLO, WORLD'

>>> 'HELLO, WORLD'.swapcase()
'hello, world'

>>> 'HELLO, #?WORLD'.swapcase()
'hello, #?world'


str.title()
ruterns str in titlecase. Examples:
>>> "py".title()
'Py'

>>> "Py thon".title()
'Py Thon'

>>> "Py Thon".title()
'Py Thon'

>>> "#py thon".title()
'#Py Thon'


str.istitle():
True if each substring is titlecqsed. Others false.
Examples:
>>> "py".istitle()
False

>>> "Py thon".istitle()
False

>>> "Py Thon".istitle()
True

>>> "Py #?Thon".istitle()
True


Note:
Characters except letters aren't checked in all the previous methods.
str.casefold():
It's similar to lower(). It returns a lowercased copy from str, but in some cases doesn't serves the purpose, because there is in other languages letters aren't existed in English itself lowercased such as "ß" in Germany therefore, we use casefold() method instead of lower() in these cases.
Example.
"hello, world".casefold()
'hello, world'

>>> "È".casefold()
'è'

>>> "ß".casefold()
'ss'


str.center(width, fillchar):
parameters:
width int.
fillchar str (optimal by default space).
returns  str padded  by the character fillchar, with width of length. str will be in the midist.
Examples:
>>> "Hi".center()
Traceback (most recent call last):
File "", line 1, in
"Hi".center()
TypeError: center() takes at least 1 argument (0 given)
>>> "Hi".center(6)
' Hi '

>>> "Hi".center(6,"_")
'__Hi__'

>>> "Hi".center(9,"#")
'####Hi###'


str.count(sub,start,end,) parameters:
sub. str.
start and end int (Optional start =0 and end=Len(str) by default)
Looks for sub in str or in the range (when it's given) [start, end] (end is not included), and returns how many times sub is existed in.
Examples:
>>> "Programming".count()
Traceback (most recent call last):
File "", line 1, in
"Programming".count()
TypeError: count() takes at least 1 argument (0 given)
>>> "Programming".count("m")
2

>>> "Programming".count("mm")
1

>>> "Programming".count("g")
2


str.encode(encoding ="UTF-8", errors="strict "):
parameters:
encoding can take ASCII ,UTF-8, base64,Latin etc.
errors can take the following:
** strict: an error will raise if there is a character can't be encoded in encoding.
** ignore: ignore any character can't be            encoded in encoding.
** namereplace: replace any character can't be encoded in encoding with its descriptive name.
** backslashreplace: replaces any character can't be encoded in encoding with backslash.
** xmlcharrefreplace: replaces any character can't be encoded in encoding with an XML character.
** replace: replaces any character can't be encoded in encoding with a question mark.
Examples:
>>> "Teléfono".encode(encoding="ascii",errors="ignore")
b'Telfono'
>>> "Teléfono".encode(encoding="ascii",errors="backslashreplace") b'Tel\\xe9fono' >>> "Teléfono".encode(encoding="ascii",errors="namereplace")
b'Tel\\N{LATIN SMALL LETTER E WITH ACUTE}fono'
>>> "Teléfono".encode(encoding="ascii",errors="replace")
b'Tel?fono'
>>> "Teléfono".encode(encoding="ascii",errors="xmlcharrefreplace")
b'Teléfono'
>>> "Teléfono".encode(encoding="ascii",errors="strict")
Traceback (most recent call last):
File "", line 1, in
"Teléfono".encode(encoding="ascii",errors="strict")
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: rordinal not in range(128)
>>> "Teléfono".encode(encoding="ascii") # the same as errors="strict".
Traceback (most recent call last):
File "", line 1, in
"Teléfono".encode(encoding="ascii") # the same as errors="strict".
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)

str.endswith(sub, start, end):
parameters:
like count() method.
returns True if str ends with sub or if it were existed in the range [start, end] (end not included). Otherwise false.
Example:
>>> "Programming".endswith("lg")
False
>>> "Programming".endswith("lg",0,4)
False

str.startswith():
parameters:
Similar as endswith() but checks if str or the range [start, end] starts with sub or doesn't.
Example:
>>> "Programming".startswith("p")
False
>>> "Programming".startswith("P")
True
>>> "Programming".startswith("Pr",0,4)
True

str.expandtabs( tabsize):
parameters:
tabsize .(Optional) int.
changes tab-size with tabsize-space times.
Examples:
>>> "py thon".expandtabs()
'py thon'
>>> "py\tthon".expandtabs(2)
'py thon'
>>> "py\tthon".expandtabs(4)
'py thon'
>>> "py\tthon".expandtabs(16)
'py thon'
>>> "py\tthon".expandtabs(20)
'py thon'

str.find(sub, start, end):
parameters:
The same as count() method.
find() searches in str or in the range [start, end] for sub and returns the starting index of the first occurrence of sub, if sub were not found in str find() returns -1.
Examples:
>>> "Programming".find("m")
6
>>> "Programming".find("m",1,5)
-1

rfind():
Like find() preforms the  same task but it returns the  starting index of the last occurrence. If sub isn't found in str it returns -1.
Examples:
>>> "Programming".rfind("m")
7

str.index():
It's similar as find() but if sub weren't found in str ValueError will raise.
Examples:
>>> "Programming".index("m",1,5)
Traceback (most recent call last):
File "", line 1, in
"Programming".index("m",1,5)
ValueError: substring not found

str.rindex():
It's similar as rfind() but if sub weren't found in str ValueError will raise.
Examples:
>>> "Programming".rindex("m")
7
>>> "Programming".rindex("m",1,5)
Traceback (most recent call last):
File "", line 1, in
"Programming".rindex("m",1,5)
ValueError: substring not found

str.format(*kargs,**kwargs):
parameters:
*kargs   key arguments simple parameters ("*" means you can pass unlimited of them).
**kwargs Key word arguments any parameter of the form " kwarg= its value" (** as *).
This method is so useful and flexible, it is used to format stringds.
Examples:
>>> a="apples"
>>> b="bananas"
>>> "Do you want {} or {}?".format(a,b)
'Do you want apples or bananas?'
>>> "Do you want {0} or {1}?".format(a,b) # using an index.
'Do you want apples or bananas?'
>>> "Do you want {1} or {0}?".format(a,b)
'Do you want bananas or apples?'
>>> table={1:"coffee",2:"tea"}
>>> "Do you want to drink {0[1]} or {0[2]}?".format(table)
'Do you want to drink coffee or tea?'
>>> point={"x":2,"y":3}
>>> "point({x}; {y})".format(**point)
'point(2; 3)'
>>> "Do you love {b} or {a}?".format(a="birds",b="fish") # kwargs.
'Do you love fish or birds?'
>>> " {0:d} in bin= {0:b}, in oct= {0:o}, in hex= {0:x} ".format(14)
' 14 in bin= 1110, in oct= 16, in hex= e '
>>> " {0:X} hex uppercase, {0:x} hex lowercase".format(10)
' A hex uppercase, a hex lowercase'

str.format_map(mapping):
parameters:
mapping      any mapping object.
like format() but only takes mappings as a parameter.
Examples:
>>> point={"x":2,"y":3}
>>> "point({x}; {y})".format_map(point)
'point(2; 3)'

str.isalnum():
True if str  contains only letters or numerics or both. Otherwise false.
Examples:
>>> "avg132٣۹٤٥".isalnum()
True
>>> 'avg'.isalnum()
True >>> '32٣۹'.isalnum()
True
>>> "تЌЫϚϛϜϢ¹²³".isalnum()
True

str.isalpha():
True if str contains only letters. Otherwise false.
Example
>>> "abcABCÈتÙß".isalpha()
True
>>> "ت".isalpha()
True
>>> "ЌЫϚϛϜϢ".isalpha()
True

str.isascii():
True if all characters in str are ASCIIs. Otherwise false
Visit this website to learn more about ASCIIs
Example:
>>> "ت".isascii()
False
>>> 'ЌЫϚϛϜϢ'.isascii()
False
>>> "é".isascii()
False
>>> "123abcEDF _'(|[{:;,!?§".isascii()
False
>>> "123abcEDF _'(|[{:;,!?".isascii()
True
>>> "§".isascii()
False

str.isdecimal():
True if str represents a decimal. str. Otherwise, false.
Examples:
>>> "12".isdecimal()
True
>>> "12.20".isdecimal()
False
>>> "١٢٣۹٤٥٦٨۵".isdecimal()
True
>>> "0123456789".isdecimal()
True
>>> "¼½¾".isnumeric()
True

str.isdigits():
True if all the of str are digits. Otherwise, false.
Examples:
>>> "١٢٣۹٤٥٦٨۵".isdigit()
True
>>> "0123456789".isdigit()
True
>>> "¹²³".isdigit()
True
>>> "12.32".isdigit()
False
>>> "¼½¾".isdigit()
False

str.isnumeric():
True if str is numerical. Otherwise false.
Note:
any decimal is an numerical.
Examples:
>>> "١٢٣۹٤٥٦٨۵".isnumeric()
True
>>> "0123456789".isnumeric()
True
>>> "¹²³".isnumeric()
True

str.isidentifier():
True if str is an identifier. Otherwise False.
str is an identifier if it was contains only letters, numbers, or underscore and doesn't start with a number.
Examples:
>>> "python".isidentifier()
True
>>> "py__thon".isidentifier()
True
>>> "__python".isidentifier()
True
>>> "123python".isidentifier()
False
>>> "pyth?#on".isidentifier()
False

str.isprintable():
True if the characters in str are printable. Otherwise False.
 Non printable characters are like \n, \t    etc.
The 31st chacrs are non printable
Examples:
>>> "\n".isprintable()
False
>>> "\t".isprintable()
False
>>> "abc".isprintable()
True

str.isspace():
True if str is only space. Otherwise False.
Examples:
>>> "abc".isspace()
False
>>> "".isspace()
False
>>> " ".isspace()
True
>>> "\n".isspace()
True
>>> "\t".isspace()
True

str.join(iterable):
parameters:
iterable  any iterable object returns strings as outputs. Note!. str works as a separator between the iterable's items.
Examples:
>>> string="_"
>>> iterable="py"
>>> iterable1=("p","y")
>>> iterable2=["p","y"]
>>> iterable3={"p":None,"y":None}
>>> string.join(iterable)
'p_y'
>>> string.join(iterable2)
'p_y'
>>> string.join(iterable3)
'p_y'
>>> string.join(iterable1)
'p_y'
>>> iterable4={1:None,"y":None}
>>> string.join(iterable4) # output is 1, not str.
Traceback (most recent call last):
File "", line 1, in
string.join(iterable4) # output is 1, not str.
TypeError: sequence item 0: expected str instance, int found

str.ljust(width, fillchar):
parameters:
width:    int the length of the output string.
fillchar:  str  (Optional " " by default) a character that will be filled with.
Fills the right side of str with fillchar.
Examples
>>> "C".ljust()
Traceback (most recent call last):
File "", line 1, in
"C".ljust()
TypeError: ljust() takes at least 1 argument (0 given)
>>> "C".ljust(3)
'C '
>>> "C".ljust(3,"#+")
Traceback (most recent call last):
File "", line 1, in
"C".ljust(3,"#+")
TypeError: The fill character must be exactly one character long
>>> "C".ljust(3,"+")
'C++'

str.rjust():
The same as ljust but fills the left side of str.
Examples:
>>> "C".rjust(3,"+")
'++C'

str.strip(char):
parameters:
char: str (Optional " " by default).
removes any substring could be consisted of char's characters from the beginning and the end. Removing stops if there is a character isn't existed in char.
Example:
>>> string="__#12_What's your name?+-*/"
>>> string.strip()
"__#12_What's your name?+-*/"
>>> string.strip("_#12+-*/")
"What's your name?"

str.lstripe():
The same as stripe() but in the right.

Examples:

>>> string="__#12_What's your name?+-*/"
>>> string.rstrip("_#12+-*/")
"__#12_What's your name?"

str.lstripe():
The same as stripe() but in the left.

Examples:

>>> string="__#12_What's your name?+-*/"
>>> string.lstrip("_#12+-*/")
"What's your name?+-*/"

str.maketrans(x, y, z):
Please! focus and read the following carefully.
parameters:
x:  sometimes dictionary ( dict) and others str.
y and z:  always str. (Optional).
**If x were the only given parameters, it has to be a dict.
**If y were given x has to be an str.
**If z were given y is required.
If x were a dict it will look like this:
x={key1:value1, k2:v2, k3:v3, ..,..}.
maketrans() returns a dict looks like this: { str's item : its replacement }.
Case1:
In this case key can be:
A character or
Its Unicode representation (integer).
Value can be:
A character
Its Unicode representation (integer) or
The keyword None
Any character is replaced with None will be deleted.
maketrans() replaces any key of x with its dependent value.
Example:

>>> string= "Programming language"
>>> table={'a':1,'m':2,'g':3}
>>> string.maketrans()
Traceback (most recent call last):
File "", line 1, in
string.maketrans()
TypeError: maketrans() takes at least 1 argument (0 given)
>>> string.maketrans(table)

{97: 1, 109: 2, 103: 3}
>>> chr(97)
'a'

Case2:
Remember! in case2 and 3 x is an str.
If y were given, x and y must be of equal length, or so ValueError will raise.
maketrans() replaces any character in x with one has the same index in y.
Example:
>>> string.maketrans("amg",123)
Traceback (most recent call last):
File "", line 1, in
string.maketrans("amg",123)
TypeError: maketrans() argument 2 must be str, not int
>>> string.maketrans("amg","123")
{97: 49, 109: 50, 103: 51}
>>> chr(49)
'1'

Case3:
Here, y doesn't have to be equal of  length with x and y.
If y were given, the same as case2 but also will replace any character of y with the keyword None.
Example:
>>> string.maketrans("amg","123","uo")
{97: 49, 109: 50, 103: 51, 117: None, 111: None}

str.translate( table):
parameters:
table dict it's the output of maketrans().
The same as maketrans() but returns a string.
Example:
>>> string= "Programming language" >>> string.translate()
Traceback (most recent call last):
File "", line 1, in
string.translate()
TypeError: translate() takes exactly one argument (0 given)
>>> string.translate(string.maketrans(table)) # with maketran() output.
'Pro\x03r\x01\x02\x02in\x03 l\x01n\x03u\x01\x03e'
>>> string.translate(string.maketrans("amg","123"))
'Pro3r122in3 l1n3u13e'
>>> string.translate(string.maketrans("amg","123","ou")) # removes 'u' and 'o' from string.
'Pr3r122in3 l1n313e'

str.replace(oldval, newval, count):
parameters:
oldval and newval str.
court  int  ( Optional).
replace the count-occurence of oldval in str with newval. If count weren't given, it will replace all the occurrences.
Example:
>>> string= "Programming language"
>>> string.replace("m","#")
'Progra##ing language'
>>> string.replace("g","#")
'Pro#rammin# lan#ua#e'
>>> string.replace("g","#",2)
'Pro#rammin# language'
>>> string.replace("mm","#")
'Progra#ing language'
>>> string.replace("ab","#") # "ab" not found in string.
'Programming language'

str.partition( value):
parameters:
value str .
Tuples look like this (elem1, elem2, elem3 , , ,elem n, , .).
Looks in str for the occurrence of value and returns a tuple with 3 of length (3 elements):
The first element is a string that falls before value. The second element is value itself.
The third element is the rest.
If value weren't found, the first element will be str, and both of the 2nd and 3rd elements will be an enpty string.
Examples:
>>> "google".partition()
Traceback (most recent call last):
File "", line 1, in
"google".partition()
TypeError: partition() takes exactly one argument (0 given)
>>> "google".partition("g")
('', 'g', 'oogle')
>>> "google".partition("oo")
('g', 'oo', 'gle')
>>> "google".partition("m")
('google', '', '')

str.rpartition():
The same as partition() but from the right side.
Examples:
>>> "google".rpartition("g")
('goo', 'g', 'le')
>>> "google".rpartition("m")
('', '', 'google')

str.split(separator, maxsplit):
parameters:
separator   str  ( Optional None by default means whitespace).
maxsplit           int =>1( Optional  -1 by default means all the occurrence)
Splits any substring  in str is followed or preceded by separator into a list with maxsplit+1 of length. maxsplit specifies the occurrence of separator to split.
Examples:
>>> "Weather is nice today".split()
['Weather', 'is', 'nice', 'today']
>>> "Weather is nice today.".split("#",maxsplit=2)
['Weather is nice today.'] >>> "Weather_is_nice_today.".split("_",maxsplit=2) ['Weather', 'is', 'nice_today.']
str.rsplit(): The same as split() but from the right side.
Examples:
>>> "Weather_is_nice_today.".rsplit("_",maxsplit=2) ['Weather_is', 'nice', 'today.']
str.splitlines( keepends):
parameters:
keepends  bool    (Optional False by default).
Splits any substring  in str is followed or preceded by the non-printable "\n" into a list. keepends specifies if "\n" will be printed or not.
Examples:
>>> "hello\nWorld".splitlines() ['hello', 'World'] >>> "hello\nWorld".splitlines(keepends=False) ['hello', 'World'] >>> "hello\nWorld".splitlines(keepends=True) ['hello\n', 'World']
str.zfill( width):
parameters:
width        int.
Returns a "0"-left filled copy of str with width's value of length.
Examples:
>>> "A".zfill()
Traceback (most recent call last): File "", line 1, in "A".zfill() TypeError: zfill() takes exactly one argument (0 given)
>>> "A".zfill(3)
'00A'


No comments:

Post a Comment

Pages