Python string functions manipulate the string. In this post we'll learn about slicing, splitting, replacing and case conversion of string.
Slicing a part of the string.
Syntax :
variable_name[slice from character position : to position]
Example
string = "Good Morning"
print(string[5:12])
print(string[5:])
print(string[:5])
#PYTHON OUTPUT
Morning
Morning
Good
To remove any leading or trailing spaces from string using strip()
method
Example
string = " Good Morning"
one plus one is two and two plus two is four
['one', 'plus', 'one', 'is', 'two', 'and', 'two', 'plus', 'two', 'is', 'four']
print(string)
print(string.strip(' '))
#PYTHON OUTPUT
Good Morning
Good Morning
To count characters in a string using len(variable_name)
Example
string = "Good Job!"
print(len(string))
#PYTHON OUTPUT
9
Convert strings of the lower case to upper case
Example
string = "this sentence will be printed in upper case"
string_l = "THIS SENTENCE WILL BE PRINTED IN LOWER CASE"
string_c = "first character of each letter will be capitalized"
print(string.upper())
print(string_l.lower())
print(string_c.title())
#PYTHON OUTPUT
THIS SENTENCE WILL BE PRINTED IN UPPER CASE
this sentence will be printed in lower case
First Character Of Each Letter Will Be Capitalized
Replace a particular character or words in a string using variable_name.replace('character to find', 'character to replace')
Example
x = 'Today I woke up at 6 am for cricket coaching'
print(x)
print(x.replace('6', '5'))
#PYTHON OUTPUT
Today I woke up at 5 am for cricket coaching
Now to replace letters of multiple occurrences specify count in the optional parameter
Example
x = 'one plus one is two and two plus two is four'
print(x)
print(x.replace('two', 'TWO'))
print(x.replace('two', 'TWO', 1))
print(x.replace('two', 'TWO', 2))
#PYTHON OUTPUT
one plus one is two and two plus two is four
one plus one is TWO and TWO plus TWO is four
one plus one is TWO and TWO plus two is four
Some times we need to explode stings into multiple fragments for that use split()
method.
Syntax :
variable_name.split(specify character, word or symbol for split)
Example
x = 'one plus one is two and two plus two is four'
print(x)
print(x.split(' ')) #split's whitespaces
#PYTHON OUTPUT
one plus one is two and two plus two is four
['one', 'plus', 'one', 'is', 'two', 'and', 'two', 'plus', 'two', 'is', 'four']
Example
x = 'There comma, will split this string'
print(x)
print(x.split(',')) #split's comma
#PYTHON OUTPUT
There comma, will split this string
['There comma', ' will split this string']
This article was originally published in The Code Learners - Python String Functions
Top comments (0)