Python String in-built function

#pythonstring #python

sudhanshu kumar Sept 16 2020 · 1 min read
Share this

String length

# To fing length of a string, we can use len
len(string)

Find character/word in a string

# To find a character in a string, use find and it will give index of that character
string.find("n")
# If it is not able to find character , it will give index as a -1
string.find('x')

Count characters in a string

# To count no. of characters in a string, can use count method
print(string.count(' '))
print(string.count('n'))

String split operation

# To split string at certain space/character, will return list of strings after splitting
print(string.split(' '))
string.split('u')

Change strings to upper & lower case

# Changes to upper case
print(string.upper())
# Changes to lower case
print(string.lower())
# Swap case from lower to upper & upper to lower
print(string.swapcase())
print(string.title())
print(string.capitalize())

Reverse string

# Can use reversed for reversing string
print(' '.join(reversed(string)))
# We can do reverse of a string by extended slice functionality [::1], so here the third one is the optional step size 
# through which we are reversing by using step size as -1
print(string[::-1])

Removing characters from the end of the string

string_a =" ineuron "
# Strip will remove white space from both end of the strings
string_a.strip(" ")
# removes leading character from a string
string_a.lstrip(" ")
# removes trailing character from a string
string_a.rstrip(" ")

Join operation in string

" ".join("Welcome to ineuron")

Replace string

string_n = "greetings to ineuron"
string_n.replace("to","from")

Formatting

string.center(20,'z')
#expandtabs() will expand tab notations \t into spaces. Let's see an example to understand the concept.
'hello\thi'.expandtabs()
Comments
Read next