Python Strings

  • Strings are nothing but a set of characters.
  • Strings in python are surrounded by either single quotation (') marks, or double quotation marks (").
  • Strings are immutable(i.e we can't update a part of the string)
first_name = 'Anjaneyulu'
last_name = "B"

multiline strings

we can create multiline strings using triple quotes.

description = '''
An apple is an edible fruit produced by an apple tree.
Apple trees are cultivated worldwide and are the most widely
grown species in the genus Malus.
The tree originated in Central Asia,
where its wild ancestor, Malus sieversii, is still found today.
'''
print(description)

using strings as arrays

  • In python strings supports indexing.
  • We can access string characters with index but can't be updated by the index number.
name = "Anji"
print(name[0])
# Output: A

iterate string with for loop

  • we can iterate through strings
for x in "apple":
  print(x)

find string length

  • we can find string length with len function.
a = "Python is Awesome"
print(len(a))
# output: 17

using "in" operator with string

  • we can use in keyword to check the substring.
sentense = "Apple is awesome fruit"
is_substring = "awesome" in sentense
print(is_substring)
# Output: True

using "not in" operator with string

  • we can use not in keyword to check if the given substring not found in the given string.
sentense = "Apple is awesome fruit"
print("june" not in sentense)
# Output: True

slicing a string

we can return a range of characters by using the slice syntax. We need to specify the start and end indexes.

b = "awesome!"
print(b[2:5])
# output: eso
print(b[:5])
# output: aweso
print(b[2:])
# output: esome!
print(b[-5:-2])
# output: som
  • if start index not specified then it will consider it as 0
  • if end index is not specified then it will consider it as length of the string
  • negative index is can also used in string slicing

convert string to upper case

  • upper method to convert the string to upper case
title = "Python is a programming language"
print(title.upper())
# output: PYTHON IS A PROGRAMMING LANGUAGE

convert string to lower case

  • lower method to convert the string to upper case
title = "Python is a programming language"
print(title.lower())
# output: python is a programming language

remove white space in the string

  • strip to remove the white space from start and end of the string.
name = "  John   "
print(name.strip())
# Output: John

replace part of the string

  • replace to replace a substring with another string
s = "Jython is Awesome"
print(s.replace("J", "P"))
# Output: Python is Awesome

split string based on a seperator

  • split method is used to split the string
  • it returns a list by splitting the string based on the seperator
  • default seperator is space
title = "Google is a search engine"
print(title.split())
# Output: ['Google', 'is', 'a', 'search', 'engine']

concatenate strings

  • combine two or more strings in to one
first_name = "Anji"
last_name = "B"
full_name = first_name + last_name
print(full_name)
# Output: AnjiB

format strings with place holders

  • format method is used to format the string.
game = "cricket"
s = "I love to play {}"
print(s.format(game))
# Output: I love to play cricket
  • we can use positions for place holders
string = "I placed an order with {2}  items for {0} rupees. Exach item costs Rs.{1}."
print(string.format(100, "50", "three"))
# Output: I placed an order with three  items for 100 rupees. Exach item costs Rs.50.
  • we can also use names as place holders
string = "I placed an order with {item_count}  items for {total} rupees. Exach item costs Rs.{item_cost}."
print(string.format(item_count="three", total=100, item_cost="50"))
# Output: I placed an order with three  items for 100 rupees. Exach item costs Rs.50.

Escape characters in string

  • we use \ to escape characters in the string.
s = "Software engineering is a \"difficult\" job to do."
print(s)
# Output: Software engineering is a "difficult" job to do.
  • Find some of the escape characters below
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value

string methods

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

References