Strings
Strings
Strings
# Output: 5
→ upper()
The upper() method converts all lowercase characters in a string into uppercase characters and
returns it.
Example
message = 'python is fun'
# convert message to uppercase
print(message.upper())
# Output: PYTHON IS FUN
The syntax of upper() method is:
string.upper()
• upper() Parameters
upper() method doesn't take any parameters.
→ swapcase()
The swapcase() method returns the string by converting all the characters to their opposite
letter case( uppercase to lowercase and vice versa).
Example
name = "JoHn CeNa"
# converts lowercase to uppercase and vice versa
print(name.swapcase())
# Output: jOhN cEnA
• swapcase() Syntax
The syntax of the swapcase() method is:
string.swapcase()
• swapcase() Parameters
The swapcase() method doesn't take any parameters.
→ lower()
The lower() method converts all uppercase characters in a string into lowercase
characters and returns it.
Example
message = 'PYTHON IS FUN'
# convert message to lowercase
print(message.lower())
# Output: python is fun
• lower() Parameters()
lower() method doesn't take any parameters.
→ partition()
The syntax of partition() is:
string.partition(separator)
• partition() Parameters()
The partition() method takes a string parameter separator that separates the string at the first
occurrence of it.
→ rpartition()
The syntax of rpartition() is:
string.rpartition(separator)
• rpartition() Parameters()
rpartition() method takes a string parameter separator that separates the string at the last
occurrence of it.
• replace() Syntax
Its syntax is:
str.replace(old, new [, count])
• replace() Arguments
The replace() method can take a maximum of three arguments:
• 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
Note: If count is not specified, the replace() method replaces all occurrences of the old substring
with the new string.
→ rfind()
The syntax of rfind() is:
str.rfind(sub[, start[, end]] )
• rfind() Parameters
rfind() method takes a maximum of three parameters:
✓ sub - It's the substring to be searched in the str string.
✓ start and end (optional) - substring is searched within str[start:end]
→ count()
The count() method returns the number of occurrences of a substring in the given string.
Example
message = 'python is popular programming language'
# number of occurrence of 'p'
print('Number of occurrence of p:', message.count('p'))
# Output: Number of occurrence of p: 4
• count() Parameters
count() method only requires a single parameter for execution. However, it also has two optional
parameters:
• substring - string whose count is to be found.
• start (Optional) - starting index within the string where search starts.
• end (Optional) - ending index within the string where search ends.
Note: Index in Python starts from 0, not 1.
Example 2: Count number of occurrences of a given substring using start and end
# define string
string = "Python is awesome, isn't it?"
substring = "i"
# count after first 'i' and before the last 'i'
count = string.count(substring, 8, 25)
# print count
print("The count is:", count)
Output
The count is: 1
Here, the counting starts after the first i has been encountered, i.e. 7th index position. And, it ends
before the last i, i.e. 25th index position.
→ rstrip()
The rstrip() method returns a copy of the string with trailing characters removed
(based on the string argument passed).
Example
print(result)
string.rstrip([chars])
• rstrip() Parameters
The rstrip() removes characters from the right based on the argument (a string specifying
the set of characters to be removed).
If chars argument is not provided, all whitespaces on the right are removed from the string.
The rstrip() returns a copy of the string with trailing characters stripped.
All combinations of characters in chars argument are removed from the right of the string
until the first mismatch.
print(random_string.rstrip())
print(random_string.rstrip('si oo'))
# in 'sid oo', 'd oo' are the trailing characters, 'ood' is removed from the string
Output
this is good
this is good
this is g
www.programiz.co
→ split()
The split() method breaks down a string into a list of substrings using a chosen separator.
Example
print(text.split())
• split() Syntax
str.split(separator, maxsplit)
• split() Parameters
• separator (optional) - Specifies the delimiter used to split the string. If not provided,
whitespace is used as the default delimiter.
• maxsplit (optional) - Determines the maximum number of splits. If not provided, the
default value is -1, which means there is no limit on the number of splits.
print(text.split())
# splits using ,
print(grocery.split(', '))
# splits using :
print(grocery.split(':'))
Output
Here,
• text.split() - splits the string into a list of substrings at each space character.
• grocery.split(', ') - splits the string into a list of substrings at each comma and space
character.
• grocery.split(':') - since there are no colons in the string, split() does not split the
string.
# maxsplit: 1
print(grocery.split('#', 1))
# maxsplit: 2
print(grocery.split('#', 2))
# maxsplit: 5
print(grocery.split('#', 5))
# maxsplit: 0
print(grocery.split('#', 0))
Output
['Milk', 'Chicken#Bread#Butter']
['Milk#Chicken#Bread#Butter']
Note: If maxsplit is specified, the list will have a maximum of maxsplit+1 items.
→ splitlines()
The splitlines() method splits the string at line breaks and returns a list.
Example
# \n is a line boundary
sentence = 'I\nlove\nPython\nProgramming.'
resulting_list = sentence.splitlines()
print(resulting_list)
• splitlines() Syntax
string.splitlines([keepends])
• splitlines() Parameters
keepends(optional) - it determines whether line breaks are included in the resulting list or
not. It's value can be True or any number.
If there are not line break characters, it returns a list with a single item (a single line).
grocery = 'Milk\nChicken\nBread\rButter'
print(grocery.splitlines())
Output
In the above example, we have used the splitlines() method to split the grocery string
i.e. 'Milk\nChicken\r\nBread\rButter' at the line breaks.
Here, grocery.splitlines() splits grocery at line break '\n' and returns a list '['Milk', 'Chicken',
'Bread', 'Butter']' after removing the line break.
→ startswith()
The startswith() method returns True if a string starts with the specified prefix(string). If not,
it returns False.
Example
print(message.startswith('Python'))
# Output: True
• startswith() Parameters
# returns False
print(result)
# returns True
print(result)
# returns True
print(result)
Output
False
True
True
# start parameter: 7
print(result)
# start: 7, end: 18
print(result)
print(result)
Output
True
False
True
→ endswith()
The endswith() method returns True if a string ends with the specified suffix. If not, it
returns False.
Example
print(message.endswith('fun'))
# Output: True
• endswith() Parameters
# returns False
print(result)
# returns True
print(result)
# returns True
print(result)
Output
False
True
True
Example 2: endswith() With start and end Parameters
# start parameter: 7
result = text.endswith('learn.', 7)
print(result)
# start: 7, end: 26
# Returns False
print(result)
# returns True
print(result)
Output
True
False
True
→ isnumeric()
The isnumeric() method checks if all the characters in the string are numeric.
Example
pin = "523"
print(pin.isnumeric())
# Output: True
• isnumeric() Syntax
string.isnumeric()
• isnumeric() Parameters
print(symbol_number.isnumeric())
text = "Python3"
print(text.isnumeric())
Output
True
False
In the above example, we have used the isnumeric() method to check whether every
character in symbol_number and text is numeric or not.
The isnumeric() method returns True with these characters. For example
superscript_string = '²3455'
print(superscript_string.isnumeric())
fraction_string = '½123'
print(fraction_string.isnumeric())
Output
True
True
Here, we have used the isnumeric() method with strings that contain superscript and
fraction.
• superscript_string.isnumeric() -returns True because '²3455' contains all numeric
characters.
• fraction_string.isnumeric() - returns True because '½123' contains all numeric
characters.
→ index()
The index() method returns the index of a substring inside the string (if found). If the
substring is not found, it raises an exception.
Example
result = text.index('is')
print(result)
# Output: 7
• index() Syntax
• index() Parameters
• If substring exists inside the string, it returns the lowest index in the string where
substring is found.
• If substring doesn't exist inside the string, it raises a ValueError exception.
result = sentence.index('Java')
Output
result = sentence.index('Java')
Note: Index in Python starts from 0 and not 1. So the occurrence is 19 and not 20.
print(sentence.index('ing', 10))
# Substring is searched in 'gramming is '
print(sentence.index('fun', 7, 18))
Output
15
17
print(quote.index('fun', 7, 18))
The escape sequence is used to escape some of the characters present inside a string.
Suppose we need to include both a double quote and a single quote inside a string,
Since strings are represented by single or double quotes, the compiler will treat "He said,
" as a string. Hence, the above code will cause an error.
print(example)
\\ Backslash
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed