A complete Guide of String in Python

In this Python article, we will discuss the string data type and we will cover a lot of functions and operations that we can perform on a string with some examples.

1. What is a string in Python?

string is defined as a sequence of Unicode characters. Strings are an array of bytes representing Unicode.

In python, there are two ways to represent or create a string. We can either use a single quote ' ' or a double quote " ". If it is a multi-line string then we can denote it by using triple quotes, ''' or """

Note: If the string has started with a double-quote then it must end with a double-quote and if the string has started with a single quote then it must end with a single quote.

#An example of string
str = "This is single line string"
print(str)

str = """This is 
      multiple line string"""
print(str)
Output
This is single line string
This is 
multiple line string

1.1. How to use quotes within a string?

If we want to keep a single quote inside the string then we have to use a double quote at the start and end of the string and vice versa.

#An example of string
str="This is 'single' line string"
print(str)
s='This is "single" line string'
print(s)

Output
This is 'single' line string
This is "single" line string

1.2. Are Strings immutable in Python?

string are immutable which means that item cannot be assigned to a particular index value of a string, it will give an error.

Immutability also means that if we perform any operation on a string then it always creates a new string object and the old string is never changed. We can check this by assigning a new value to the variable and check the reference value using id() function. id() function is used to check the unique identifier of an object.

x="hel"
print(id(x))
x = "hel" + "lo"
# This id will refer to new object
# and hence it proves immutability
print(id(x))

str="This is single line string"
print(str)
str[7]='x'
print(str)
Output
4393966512
4393966384
This is single line string
Traceback (most recent call last):
   File "", line 1, in 
 TypeError: 'str' object does not support item assignment
This is single line string

1.3. How to access characters in a string?

We can use a slicing operator [] with the string to slice the string according to the index value just like we use it with a list or a tuple.

We can use the indexing or slicing to access individual characters and range of characters respectively. Index starts from 0.

Python-String-Index
Python-String-Index
>>> str="Hello Codingeek"

# Second character
>>> print("Sliced string is: ",str[2])
Sliced string is:  l

# from 5th too 12th character
>>> print("Sliced string is: ",str[4:12])
Sliced string is:  o Coding

# from 7th to end
>>> print("Sliced string is: ",str[6:])
Sliced string is:  Codingeek

# from start to  5th
>>> print("Sliced string is: ",str[:5])
Sliced string is:  Hello

# from second last to last
>>> print("Sliced string is: ",str[-2:])
Sliced string is:  ek

# from start to second last
>>> print("Sliced string is: ",str[:-2])
Sliced string is:  Hello Codinge

1.4. How to display string without a variable?

We can also display the string without assigning it to any variable.

print("However")
print('However')
Output
However
However

1.5. How to iterate through string in Python?

We can use for loop to iterate over a string and access each character of that string.

for i in 'coding':
  print(i)
Output
c
o
d
i
n
g

1.6. How to get length of string?

To get the length of the string, we use in-built function len().

a = "codingeek"
b = len(a)
print(b)
Output
9

1.7. How to test if string contains a word?

We can also find any character in a string by using in keyword. It will return a TRUE or FALSE value.

str= "Nature is the best gift to us"
print("gift" in str)
Output
True

We can implement the above example with the help of if keyword.

str= "Nature is the best gift to us"
if "best" in str:
  print("Yes, 'best' is present")
Output
Yes, 'best' is present

1.8. How to update or delete a string in Python?

In Python, we cannot update or delete characters from any given string. Trying to do so will give us an error because python does not support item assignment or item deletion from any given string.

But we can delete the entire String with the use of a built-in keyword del. As we know that strings are immutable, so we cannot change any particular element of a string once it has been assigned. We can only reassign a new string to the same variable.

str = "I am learning Python"
print("Current String: ")
print(str)

str[6] = 'p'  # Updating one character 
print("\nNew string: ")
print(str)
Output
Current String: 
I am learning Python
Traceback (most recent call last):
  File "C:/Users/ASUS/Documents/faketest.py", line 5, in 
    str[6] = 'p'  # Updating one character
TypeError: 'str' object does not support item assignment

Now let’s update the entire string with an example.

str="Today is Friday"
print(str)
str="Today is Saturday"
print(str)
str="Today is Sunday"
print(str)
Output
Today is Friday
Today is Saturday
Today is Sunday

Let’s check if we can delete single character of any given string or not.

str = "I am learning Python"
print("Current String: ")
print(str)

del str[9]    #Deleting a character 
print("\nAfter deletion: ")
print(str)
Output
Current String: 
I am learning Python
Traceback (most recent call last):
  File "C:/Users/ASUS/Documents/faketest.py", line 5, in 
    del str[9]    #Deleting a character
TypeError: 'str' object doesn't support item deletion

After deletion: 
I am learning Python

Now lets implement an example that deletes the whole string.

str = "I am learning Python"
print(str)

del str
print(str)
Output
I am learning Python
<class 'str'>

1.9. How to use Logical Operations on a string?

We can also use different logical operations on strings. Let’s implement it with an example.

str_1 = 'Codin'
str_2 = 'geek'

print(repr(str_1 and str_2))   #It will return str_2   
print(repr(str_2 and str_1))   #It will return str_1   
print(repr(str_1 or str_2))    #It will return str_1   
print(repr(str_2 or str_1))    #It will return str_2 
print(repr(not str_1))         #It will return false   
print(repr(not str_2))         #It will return false
Output
'geek'
'Codin'
'Codin'
'geek'
False
False

These are the most common and important operations that can be performed on any string we studied each of them with various interesting examples. Now, we will explore more properties assigned with string in python.


2. How to use Escape Sequence on Strings in Python

Suppose we want to print a string that will contain a double quote and a single quote inside the string, but as we know that we cannot use two double-quotes or two single-quotes at the same time as printing such strings with single and double quotes in it causes SyntaxError.

Here comes some way to print such a string. We can either use Triple Quotes or Escape sequences to print such strings.

Escape sequences are a special set of in-built features in python that start with a backslash and it is interpreted differently in the program or the string. If we use single quotes to represent a string, then all the single quotes present in the string must be escaped and the same is done for double-quotes.

Let’s take an small example to see how it works

str = '''I'm a "Codingeekian"'''
print("Using triple quote: ")
print(str)
 
str = 'I\'m a "Geek"'
print("\nUsing Escape Sequence Single Quote: ")
print(str)
  
str = "I'm a \"Geek\""
print("\nUsing Escape Sequence Double Quotes: ")
print(str)
  
str = "D:\\Python\\Lib\\"   #printing path with escape sequence
print("\nUsing Escape Backslashes: ")
print(str)
Output
Using triple quote: 
I'm a "Codingeekian"

Using Escape Sequence Single Quote: 
I'm a "Geek"

Using Escape Sequence Double Quotes: 
I'm a "Geek"

Using Escape Backslashes: 
D:\Python\Lib\

Now a situation may arise when you want to keep the single slashes in the string. In such cases to ignore the escape sequences present in a string, r or R is used, which implies the string to be a raw string and escape sequences inside it are to be ignored.

str = R"This is \a56\y65\t76\s6b\n73 in \x84\x69\x12"
print("This is a raw string: ")
print(str)
Output
This is a raw string: 
This is \a56\y65\t76\s6b\n73 in \x84\x69\x12

3. Formatting of Strings in Python

In python, we can format any given string with the use of format() keyword which is a very versatile and powerful tool used for string formatting.

The format method uses curly braces {} as placeholders that hold arguments depending on positions or keywords to specify the sequence.

# An simple example for Positional Formatting
str = "{3} {1} {2} {0}".format('Platform', 'Geek', 'Learing', 'Coding')
print("String according to position format: ")
print(str)
  
# Keyword Formatting
str = "{c} {g} {l} {p}".format(g = 'GEEK', c = 'CODING', p = 'PLATFORM', l = 'LEARNING')
print("\nString according to keyword format: ")
print(str)
Output
String according to position format: 
Coding Geek Learing Platform

String according to keyword format: 
CODING GEEK LEARNING PLATFORM

We can use this technique with different integers such as binary, hexadecimal, octal, decimal, etc., and format specifier also helps to make round or display in the exponent form for float data types.

# Integer value formatting
str = "{0:b}".format(19)
print("\nBinary value of 19 is ")
print(str)
  
# Float value formatting
str = "{0:e}".format(247.1794)
print("\nExponent value of 247.1794 is ")
print(str)
  
# Round off value formatting
str = "{0:.2f}".format(2/9)
print("\ntwo-ninth is ")
print(str)
Output
Binary value of 19 is 
10011
Exponent value of 247.1794 is 
2.471794e+02
two-ninth is 
0.22

The old way of style formatting was done by using the % operator, it did not involve the use of the format method.

# Old Style Formatting
num = 16.4531795
print("Formatting in old format(3.2f): ")
print('%3.2f' %num)
Output
Formatting in old format(3.2f): 
16.45

In the above example, 3 means look for 3 numbers after decimal and 2 means to round it up to 2 decimal places.


4. Built-in Functions for string in Python

Let’s consider that we have a string with the name str. We will see what in-built functions python provides to apply on a string.

Some commonly used string functions are listed below

str.isdecimalTo check if a string’s all character is decimal.
str.isalnumTo check if a string’s all character is alphanumeric.
str.istitleTo check if a string’s all character is a title cased string.
str.partitionsplits the string when the first separator is encountered and returns a tuple.
str.isidentifierTo check if a string is a valid identifier.
str.lento find the length of the string.
str.rindexif the substring is found, it returns the highest index of the substring inside the string.
str.maxGives back the highest alphabetical character in a string.
str.minGives back the minimum alphabetical character in a string.
str.splitlinesGives back a list of lines in the string.
str.capitalizeGives back a word with its first character capitalized.
str.expandtabsIt expands tabs in a string and replaces them with one or more spaces
str.findGives back the lowest index in a substring.
str.rfindGives back the highest index.
str.countGives back the number of (non-overlapping) occurrences of substring sub in string
str.lowerGives back a copy of str, but with all uppercase letters converted to lower case.
str.splitGives back a list of the words of the string, if the optional second argument separator is absent.
str.rsplit()Gives back a list of the words of the string str, scanning str from the end.
str.splitfieldsGives back a list of the words when only used with two arguments.
str.joinConcatenate a list or tuple of words with intercede occurrences of the separator.
str.strip()Gives back a copy of the string after removing the leading and trailing characters.
str.lstripGives back a copy of the string with only leading characters removed.
str.rstripGives back a copy of the string with only trailing characters removed.
str.swapcaseConverts lower case letters to upper case and vice versa.
str.translatetranslates the characters using table
str.upperconverts lower case letters to upper case.
str.ljustleft-justify in a field of a given width.
str.rjustRight-justify in a field of a given width.
str.center()Center-justify in a field of a given width.
str.zfillIt pads a numeric string on the left with zero digits until the given width is reached.
str.replaceGives back a copy of string str with all occurrences of old substring replaced by new.
str.casefold()Gives back the string in lowercase which can be used for caseless comparisons.
str.encodeEncodes the string into particular encoding supported by Python. The default encoding is utf-8.
str.maketransGives back a translation table usable for str.translate()
str.ascii_lettersConcatenates the ascii_lowercase and ascii_uppercase constants.
str.ascii_lowercaseConcatenates lowercase letters
str.ascii_uppercaseConcatenates uppercase letters
str.digitsGives back digit in strings
str.hexdigitsGives back hexadigit in strings
str.lettersConcatenates the strings lowercase and uppercase
str.lowercaseGives back string that must contain lowercase letters.
str.octdigitsGives back octadigit in a string
str.punctuationGives back ASCII characters having punctuation characters.
str.printableGives back a String of printable characters.
str.endswith()Gives back True if a string ends with the given suffix.
str.startswith()Gives back true if a string starts with the given prefix.
str.isdigit()Gives back “True” if all characters in the string are digits.
str.isalpha()Gives back “True” if all characters in the string are alphabets.
str.isdecimal()Gives back true if all characters in a string are decimal.
str.format()one of the string formatting methods in Python3, which allows multiple substitutions and value formatting.
str.uppercaseGives back a string that must contain uppercase letters.
str.whitespaceGives back a string that contains all characters that are considered whitespace.
Built-in Functions for string in Python

5. Conclusion

In this article we have covered every detail related to string with interesting examples.

  • What is a String in Python with different operations and why is it immutable.
  • How to slice, iterate, get length, check membership of a word.
  • How to use Escape Sequence on Strings
  • Formatting of Strings
  • Built-in functions for string

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x