Operations and Usage of Strings - Python

  • String is  a one of the built-in data types in python.
  • We can form strings by combining zero or more characters.
  • It is immutable data type.
  • We cannot change/modify the data in the string.

How to create string in python ?

# case1: empty string
s = ''
print(type(s))
# Output: str
s = str()
print(type(s))
# Output: str
print(s)
# Output: ''
# case2: string
s = "hello world"
print(s)
# Output: 'hello world'
print(type(s))
# Output: str

How to find length of a string in python ?

s = "find length of the string"
print(s)
# Output: find length of the string
print(len(s))
# Output: 25

How to capitalize the string in python ?

s1 = "hello world"
s2 = s1.capitalize()
print(s2)
# Output: Hello world
print(s1)
# Output: hello world

How to set string in the middle of certain length ?

s1 = "hi"
s2 = s.center(10)
print(s1)
# Output: 'hi'
print(s2)
# Output: ' hi '

How to count number of occurrences of a string in a given string?

s= "A Jewish father and his family are surrounded by Nazi death camps."
print(s.count('r'))
# Output: 4
print(s.count('th'))
# Output: 2

How decode the given string to a codec [utf-8, ascii, base64, etc] in python ?

s = 'confrčres'
print(s)
# Output: confrčres
s1 = s.decode("utf-8")
print(s1)
# Output: confrčres
s3 = s.decode("ascii")
# Output: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 5: ordinal not in range(128)
s4 = s.decode("base64")
print(s2)
# Output: r�߮��

How encode the given string to a codec [utf-8, ascii, base64, etc] in python ?

s = "encode"
output = s.encode("base64")
print(output)
# Output: ZW5jb2Rl
output = s.encode("ascii")
print(output)
# Output: encode
output = s.encode("utf-8")
print(output)
# Output: encode
print(s)
# Output: encode

How to check whether the given string ends with a string or not ?

s = "this is not an end"
output = s.endswith("end")
print(output)
# Output: True
output = s.endswith("and")
print(output)
# Output: False

How to print output in a table format with method expandtabs in python ?

str.expandtabs(n) keeps track of the current cursor position on each line, and replaces each tab character it finds with the number of spaces from the current cursor position to the next tab stop. The tab stops are taken to be every n characters.
s = "123\t12345\t1234\t1\n12\t1234\t123\t1"
print(s.expandtabs(10))
# Output:
# 123 12345 1234 1
# 12 1234 123 1
print(s.expandtabs(5))
# 123 12345 1234 1
# 12 1234 123 1

How to get index position of substring in string ?

s = "let's find the index of substring"
index = s.find("sub")
print(index)
# Output: 24
index = s.find("not found")
print(index)
# Output: -1
s = "let's find the index of substring. by using find method"
index = s.find("find")
print(index)
# Output: 6
Note: It only returns first occurrence string index. It return -1 if string not found.

how to format strings in python using "format" method ?

'Sam has {0} red balls and {1} yellow balls'.format(12, 31)
# Output: Sam has 12 red balls and 31 yellow balls
'Sam has %d red balls and %d yellow balls'%(12, 31)
"Floating point {0:.2f}".format(345.7916732)
# Output: Floating point 345.79
d >>> for integers
f >>> for floating point numbers
b >>> for binary numbers
o >>> for octal numbers
x >>> for octal hexadecimal numbers
s >>> for string
e >>> for floating point in exponent format

How to convert string to upper case or capital letters in python?

s = "this is STring"
upper_case = s.upper()
print(upper_case)
# Output: THIS IS STRING

How to convert string to upper case or capital letters in python?

s = "this is string"
upper_case = s.upper()
print(upper_case)
# Output: THIS IS STRING

How to convert string to lower case or small letters in python?

s = "THIS is STRING"
lower_case) = s.lower()
print(lower_case)
# Output: this is string

How to convert string to title case in python?

s = "THIS is STRING"
title_case = s.title()
print(title_case)
# Output: This Is String

How to check whether string contains only alphabets or not in python?

s = "THIS is STRING 123 @#$"
out = s.isalpha()
print(out)
# Output: False
s = "THIS"
out = s.isalpha()
print(out)
# Output: True

How to check whether string contains only alphabets and numbers in python?

s = "THIS is STRING 123 @#$"
out = s.isalnum()
print(out)
# Output: False
s = "THIS1234"
out = s.isalnum()
print(out)
# Output: True

How to check whether string contains only numbers or not in python?

s = "THIS is STRING 123 @#$"
out = s.isdigit()
print(out)
# Output: False
s = "1234"
out = s.isdigit()
print(out)
# Output: True

How to check whether given string is lower case or not in python?

s = "THIS is STRING 123 @#$"
out = s.islower()
print(out)
# Output: False
s = "1234-it's me"
out = s.islower()
print(out)
# Output: True

How to check whether given string is in upper case or not in python?

s = "THIS is STRING 123 @#$"
out = s.isupper()
print(out)
# Output: True
s = "1234-it's me"
out = s.isupper()
print(out)
# Output: False

How to check whether given string is space or not in python?

s = "this is not a white space"
out = s.isspace()
print(out)
# Output: False
s = "\t \n "
out = s.isspace()
print(out)
# Output: True
# String that only contains white spaces like tabs, space, new lines etc. can be considered as space.

How to check whether given string is in "title case' or not in python?

s = "This Is Title"
out = s.istitle()
print(out)
# Output: True
s = "This is Not a Title case"
out = s.istitle()
print(out)
# Output: False

How to join a list of strings with a given string in python ?

l = ["this", "is", "a", "string"]
# let's join the string with "-"
new_string = "-".join(l)
print(new_string)
# Output: this-is-a-string

How to remove surrounding spaces in a given string in python ?

s = "  \t this is me   \t \n"
new_string = s.strip()
print(repr(new_string))
# Output: 'this is me'

How to remove left side surrounding spaces in a given string in python ?

s = "  \t this is me   \t \n"
new_string = s.lstrip()
print(repr(new_string))
# Output: 'this is me \t \n'

How to remove right side surrounding spaces in a given string in python ?

s = "  \t this is me   \t \n"
new_string = s.rstrip()
print(repr(new_string))
# Output: ' \t this is me'

How to replace a string with a given string python ?


s = "this is batta. I'm a developer."
# replace "developer" with designer
new_string = s.replace("developer", "designer")
print(new_string)
# Output: this is batta. I'm a designer.

How to split a string to list of words using marker ?


s = "this is batta. I'm a developer."
# default marker is space
l = s.split()
print(l)
# Output: ['this', 'is', 'batta.', "I'm", 'a', 'developer.']
l = s.split("batta")
print(l)
# Output: ['this is ', ". I'm a developer."]
s = "line1 \n line2"
l = s.splitlines()
# Output: ['line1 ', ' line2']
Note: splitlines only considers "\n" as marker. but split considers whitespace as marker.

Buy a product to Support me