Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
Scarica il documento per vederlo tutto.
vuoi
o PayPal
tutte le volte che vuoi
THIS SHOULD ALL BE UPPERCASE.
tHiS sHoUlD bE mIxEd CaSeD.
In [ ]: # @title Example 2: `swapcase()` with Non-English character
text = "groß"
# converts text to uppercase
print(text.swapcase())
# performs swapcase() on text.swapcase()
print(text.swapcase().swapcase())
print(text.swapcase().swapcase() == text) # Remember! Not necessarily, string.swapcase().swapcase() == string
GROSS
gross
False swapcase() 'groß' 'ß' 'ss'
In the above example, we have used the method with the German word . The letter is in English.
Here:
text.swapcase() 'groß' 'GROSS'
: converts to uppercase i.e.
text.swapcase().swapcase() 'GROSS' 'gross' 'gross' 'groß'
: converts to lowercase i.e. Hence the new string is not equal to text (= ).
split() method
split()
The method splits a string at the specified separator and returns a list of substrings.
split() split()
### Syntax of The syntax of method is:
string.split(separator, maxsplit)
split() split()
### Parameters method takes a maximum of 2 parameters:
separator (optional): Delimiter at which splits occur. If not provided, the string is splitted by default at whitespaces and newline characters.
maxsplit (optional): Maximum number of splits. If not provided, there is no limit on the number of splits.
split() split()
### Return Value The method returns a list of strings.
In [ ]: # @title Example 1: How `split()` works in Python?
text= 'Love thy\n neighbor'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread'
# splits at ',' + ' '
print(grocery.split(', '))
# Splits at ':'
print(grocery.split(':')) # there is no ':', so the output it will be the same of the variable grocery
['Love', 'thy', 'neighbor']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']
In [ ]: # @title Example 2: How `split()` works when `maxsplit` is specified?
grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print(grocery.split(', ', 2))
# maxsplit: 1
print(grocery.split(', ', 1))
# maxsplit: 5
print(grocery.split(', ', 5))
# maxsplit: 0
print(grocery.split(', ', 0))
['Milk', 'Chicken', 'Bread, Butter']
['Milk', 'Chicken, Bread, Butter']
['Milk', 'Chicken', 'Bread', 'Butter']
['Milk, Chicken, Bread, Butter']
maxsplit maxsplit+1
N.B If is specified, the list will have a maximum of items.
strip() method
strip()
The method returns a copy of the string by removing both the leading (iniziali) and the trailing (finali) characters (based on the string argument
passed). strip() strip()
### Syntax of The syntax of method is:
string.strip(chars)
strip() strip()
### Parameters method takes a maximum of 2 parameters: strip()
chars (optional): a string specifying the set of characters to be removed from the left and right part of the string. The method removes
characters from both left and right based on the argument (a string specifying the set of characters to be removed).
N.B. If the chars argument is not provided, all leading and trailing whitespaces are removed from the string.
strip() strip()
### Return Value The method returns a copy of the string with both leading and trailing characters stripped.
REMEMBER!
When the character of the string in the left mismatches with all the characters in the chars argument, it stops removing the leading characters. Similarly, when the
character of the string in the right mismatches with all the characters in the chars argument, it stops removing the trailing characters.
In [ ]: # @title Example: Working of the `strip()` method
string = ' xoxo love xoxo '
# Leading and trailing whitespaces are removed
print(string.strip())
# All <whitespace>,x,o,e characters in the left and right of string are removed
print(string.strip(' xoe'))
# Argument doesn't contain space
# No characters are removed. ('x' is not removed because it is in the middle of the string, and not at the beginning o
r at the end)
print(string.strip('stx'))
string = 'android is awesome'
print(string.strip('an'))
xoxo love xoxo
lov
xoxo love xoxo
droid is awesome string.strip()
Here, we can see that the first expression without any arguments removed the whitespaces from the left and right of string.
string.strip(' xoe') : Removes all whitespace, x, o, and e that lead or trailed the string.
string.strip('stx') : Since string has whitespace at the beginning and end, this expression does not change the string. x is not removed since it is at
the middle of the string (whitespaces lead and trail the string)
string.strip('an') : Removes an leading the string.
join() method
join()
The method returns a string by joining all the elements of an iterable (list, string, tuple), separated by the given separator, that must be a string.
join() join()
### Syntax of The syntax of method is:
separator.join(iterable)
join() join()
### Parameters The method takes an iterable (objects capable of returning its members one at a time) as its parameter.
Some of the example of iterables are:
Native data types: List, Tuple, String, Dictionary and Set.
__iter__() __getitem()__
File objects and objects you define with an or method.
join()
N.B The method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by
join()
a string separator (the string on which the method is called) and returns the concatenated string.
join() join()
### Return Value The method returns a string created by joining the elements of an iterable by the given string separator.
TypeError
P.S. If the iterable contains any non-string values, it raises the exception.
In [ ]: # @title Example 1: Working of the `join()` method
# .join() with lists
numList = ['1', '2', '3', '4']
separator = ', '
print(separator.join(numList))
# .join() with tuples
numTuple = ('1', '2', '3', '4')
print(separator.join(numTuple))
s1 = 'abc'
s2 = '123'
# each element of s2 is separated by s1
# '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('s1.join(s2):', s1.join(s2))
# each element of s1 is separated by s2
# 'a'+ '123'+ 'b'+ '123'+ 'b'
print('s2.join(s1):', s2.join(s1))
1, 2, 3, 4
1, 2, 3, 4
s1.join(s2): 1abc2abc3
s2.join(s1): a123b123c
In [ ]: # @title Example 2: The `join()` method with sets
# .join() with sets
test = {'2', '1', '3'}
s = ', '
print(s.join(test))
test = {'Python', 'Java', 'Ruby'}
s = '->->'
print(s.join(test))
1, 2, 3
Ruby->->Java->->Python
In [ ]: # @title Example 3: The `join()` method with dictionaries
# .join() with dictionaries
test = {'mat': 1, 'that': 2}
s = '->'
# joins the keys only
print(s.join(test))
test = {1: 'mat', 2: 'that'}
s = ', '
# this gives error since key isn't string, but integer numbers
#print(s.join(test)) # Error!
mat->that
find() method
find()
The method returns the index of first occurrence of the substring (if found). If not found, it returns -1.
find() find()
### Syntax of The syntax of method is:
string.find(substring, start, end)
find() find()
### Parameters The method takes maximum of three parameters:
substring: It is the substring to be searched in the string.
string[start:end] start end
start and end (optional): The range within which substring is searched, where the value is included, while the
start end
one is excluded. For the default value is 0, while for the default value is the end of the substring.
find() find()
### Return Value The method returns an integer value: find()
If the substring exists inside the string, it returns the index of the first occurence of the substring. So, returns the lowest index in the string
substring string[start:end]
where the sub-string is found within the slice .
-1
If a substring doesn't exist inside the string, it returns .
In [ ]: # @title Example 1: `find()` With No `start` and `end` Argument
quote = 'Let it be, let it be, let it be'
# first occurance of 'let it'(case sensitive)
result = quote.find('let it')
print("Substring 'let it':", result) # output: 11, in quanto viene stampato il più basso indice alla quale la
# sotto-stringa comincia (in questo caso è 11 perchè la lettera 'l' si trova in p
osizione 11 # all'interno della sotto-stringa [Ricorda! Gli indici iniziano da 0 e NON da 1])
# find returns -1 if substring not found
result = quote.find('small')
print("Substring 'small ':", result)
# How to use find()
if (quote.find('be,') != -1):
print("Contains substring 'be,'")
else:
print("Doesn't contain substring")
Substring 'let it': 11
Substring 'small ': -1
Contains substring 'be,'
In [ ]: # @title Example 2: `find()` With `start` and `end` Arguments
quote = 'Do small things with great love'
# Substring is searched in 'hings with great love' (that is equal to the slice quote[10:])
print(quote.find('small things', 10))
# Substring is searched in ' small things with great love' (quote[2:])
print(quote.find('small things', 2))
# Substring is searched in 'hings with great lov' (quote[10:-1], that is equal to quote[10:31], where 31 = len(quote))
print(quote.find('o small ', 10, -1))
# Substring is searched in 'll things with' (quote[6:20])
print(quote.find('things ', 6, 20))
-1
3
-1
9
replace() method
replace()
The method replaces each matching occurrence of a substring with another string.
replace() replace()
### Syntax of The syntax of method is:
string.replace(old, new, count)
replace() replace()
### Parameters The method takes maximum of three parameters:
old: the old substring we want to replace
new: new substring which will replace the old substring
count (optional): the number of times you want to replace the old substring with the new string
count replace()
N.B If is not specified, the meth