Python String basics explained with examples

Python string are one of the most widely used data type which has a bunch of very powerful predefined methods to be used by the programmer to do very processing needs.
A string is basically an ordered sequence of characters to store text-based information.

Let’s have a look into some common string operations and properties.

OperationDescription
Empty_str = ‘’Empty String
Single_quoted_str = “It’s”Any special character (except escape \ character) inside “” or ‘’ will be considered as text.
Block_str = “””… Block of strings “””Triple-quoted (applicable with both ‘’ or “”) Block of strings
Raw_str = r’\no\escape’Raw strings (no special character priviledge)
str1 + str2String concatenation
Str1 * 2Repeat same string into multiple times
Str1[i]Indexing of string
Str1[i:j]Slicing of string to get substring
Str1.find(‘xyz’)Search substring in string
Str1.rstrip()To remove spaces
Str1.replace(‘xyz’, ‘abc’)Replace any occurrence of substring “xyz” with substring “abc”
Str1.split(‘,’)Split string on delimiter
Str1.lower() or Str1.upper()Convert case of string
String basics

There are lots of very useful functions are provided by python for string datatype. In above table we have just showcased usage of some common string methods. Now, let’s discuss string methods in details.

String Literals

In Python, Strings are very easy to use when compared to other programming languages like C and it has multiple ways to define it which might make it difficult to use initially but eventually this phase will pass from the programmer’s life very quickly.

Important Points

  • Both Single and Double quoted strings are same. This makes it easier to use quote characters in the text if needed as no escape character is needed.
    • Eg: ‘test’ and “test” both are same.
  • Python string also support escape character which is Backslash “\” and one or more characters.
    • Eg: s5 = ‘t\te\ns\0t’
  • Length of string will be calculated based on how string is stored and not how string is displayed.
    • Eg: s5 = ‘t\te\ns\0t’, print (len(s5)) – 7
  • To ignore escape characters, raw strings are defined.
    • Eg: file_name_raw = r’C:\new\text.dat’
  • Triple quoted strings can also be used to add comments in code. These are very useful in case one need to add multiple lines of comments.
  • String supports saving other variable value in another variable.

Let’s have a look into some sample python code to depict string literals usage.

def print_block (x, y):
    print ('======== %s start =============' % y)
    print (x)
    print ('======== %s end   ============' % y)

s1 = 'test1 "string"'  # single quoted strings
s2 = "test2 'string'"  # double quoted strings
s3 = '''.... This is a block of strings....
        ........ creating block ...........'''
s4 = """.... This is a block of strings....
        ........ creating block ..........."""
s5 = 't\te\ns\0t'  # Escape characters usage
s6 = r"Let's try some fun with \new" # raw string
file_name = 'C:\new\text.dat' # escape characters will yield undefined names
file_name_raw = r'C:\new\text.dat' # intended name
s7 = f'File name -- {file_name_raw}'

print_block (s1, 'double quote embedded')
print_block (s2, 'single quote embedded')
print_block (s3, 'show multiline string')
print_block (s4, 'show multiline string')
print_block (s5, 'escape characters usage')
print_block (s6, 'raw string')
print_block (len(s5), 'showcase length of raw string')
print_block (file_name, 'disadvantage of not using raw string')
print_block (file_name_raw, 'usage of raw string')
print_block (s7, 'embed other variable value')

Let’s have a look into the output of above sample program.

======== double quote embedded start =============
test1 "string"
======== double quote embedded end   ============
======== single quote embedded start =============
test2 'string'
======== single quote embedded end   ============
======== show multiline string start =============
.... This is a block of strings....
        ........ creating block ...........
======== show multiline string end   ============
======== show multiline string start =============
.... This is a block of strings....
        ........ creating block ...........
======== show multiline string end   ============
======== escape characters usage start =============
t	e
st
======== escape characters usage end   ============
======== raw string start =============
Let's try some fun with \new
======== raw string end   ============
======== showcase length of raw string start =============
7
======== showcase length of raw string end   ============
======== disadvantage of not using raw string start =============
C:
ew	ext.dat
======== disadvantage of not using raw string end   ============
======== usage of raw string start =============
C:\new\text.dat
======== usage of raw string end   ============
======== embed other variable value start =============
File name -- C:\new\text.dat
======== embed other variable value end   ============

Leave a Reply

Your email address will not be published. Required fields are marked *