Python String Data Types

We learnt about Python's numeric data types in the post before this one, and now we'll learn about text sequence types, or strings.

Optional: Creating chapter-wise Python files

Let's create a directory that will house fresh Python files with code samples from each post in order to keep track of what we've learned so far from each one. For the purpose of keeping all learning in one location, this step is optional but is advised to set up.

  • Open VScode and create new folder python-with-gcptutorials
  • Inside python-with-gcptutorials create file learn_strings.py

vscode-new-file


How to create Python Strings

Write code

Write below code snippet in learn_strings.py and run the script.

Using single quotes

Python string can be created using single quotes and any double can be embedded within these strings.

   
# single quotes
str_obj_1 = 'single quotes allows embedded "double" quotes'
print(str_obj_1)
 

Run the script

To run the script click on Run -> Run Without Debugging.

run-python-script

Output

   
single quotes allows embedded "double" quotes
 

Using double quotes

Python string can be created using double quotes and any single quotes can be embedded within these strings.

   
# double quotes
str_obj_2 = "double quotes allows embedded 'single' quotes"
print(str_obj_2)
 

Output

   
double quotes allows embedded 'single' quotes
 

Using three single and double quotes

Triple quoted strings can span multiple lines and all associated whitespace will be included in the string literal.

   
# three single quotes
str_obj_3 = '''Example string with Three single quotes'''
print(str_obj_3)

# three double quotes
str_obj_4 = """Example string with Three double quotes"""
print(str_obj_4)

# multiline string with triple quotes
str_obj_5 = """This a multiline string
            that will span to two or more
            lines.
            """
print(str_obj_5)
  
 

Output

   
Example string with Three single quotes
Example string with Three double quotes
This a multiline string
            that will span to two or more
            lines.
 

We created several string objects in the code sample above in a number of different ways. Now in the next section we will see the methods available for String objects in Python.

String Methods in Python


Python String capitalize() Example

str.capitalize() returns a copy of the string with its first character capitalized and the rest lowercased.

   
# str.capitalize()
my_str = "make it Capitalized"
capitalized_str = my_str.capitalize()

print(capitalized_str)
 

Output

   
Make it capitalized
 

Python String count() Example

Python str.count(sub[, start[, end]]) returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Arguments start and end are optional here.

   
# get the count of 3 without start and end
my_str = "3 apples, 3 oranges, 3 mangoes, 3 grapes"
count = my_str.count("3")
print("Count of 3 in complete string is :", count)

# get the count of 3 with start and end
my_str = "3 apples, 3 oranges, 3 mangoes, 3 grapes"
count = my_str.count("3", 0, 5)
print("Count of 3 in sub string is :", count)
 

Output

   
Count of 3 in complete string is : 4
Count of 3 in sub string is : 1
 

Python String endswith() Example

Python str.endswith(suffix[, start[, end]]) returns True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. Arguments start and end are optional.

   
# check if string ends with "text"
my_str = "This tool will generate random text"
op = my_str.endswith("text")
print(op)

# using tuple in suffix
my_str_1 = "This tool will generate random text"
my_str_2 = "We are gradually increasing production"

op_1 = my_str_1.endswith(("production","text"))
print(op_1)

op_2 = my_str_2.endswith(("text","production"))
print(op_2)
 

Output

   
True
True
True
 

Python String startswith() Example

Python str.startswith(suffix[, start[, end]]) returns True if the string starts with the specified prefix, otherwise return False. Prefix can also be a tuple of prefixes to look for. Arguments start and end are optional.

   
# startswith example
my_str = "This tool will generate random text"
op = my_str.startswith("This")
print(op)

# using tuple in prefix
my_str_1 = "This tool will generate random text"
my_str_2 = "We are gradually increasing production"

op_1 = my_str_1.startswith(("We","This"))
print(op_1)

op_2 = my_str_2.startswith(("We","This"))
print(op_2)
  
 

Output

   
True
True
True
 

Python String find() Example

Python str.find(sub[, start[, end]]) returns the lowest index in the string where substring sub is found in string. If substring is not found it returns -1

   
# check position of "random" 
my_str = "This tool will generate random text"
op = my_str.find("random")
print(op)

# returns -1 if substring not found
op = my_str.find("abcd")
print(op)
  
 

Output

   
24
-1
 

Python String join() Example

Python str.join(iterable) returns a string which is the concatenation of the strings in iterable such as lists, tuples etc.

   
# join list of strings
my_list = ["this", "is", "sample", "string"]
op_1 = "-".join(my_list)
op_2 = ",".join(my_list)
print(op_1)
print(op_2)
  
 

Output

   
this-is-sample-string
this,is,sample,string
 

Python String partition() Example

Python str.partition(separator) returns a tuple of 3 elements. If separator is found in string than tuple contains the part before the separator, the separator itself, and the part after the separator. If separator is not found than tuple contains the string itself, followed by two empty strings.

   
# partition method example
my_str = "Using separator ~ to split the string."
op_1 = my_str.partition("~")
print(op_1)

op_2 = my_str.partition("-")
print(op_2)
 
 

Output

   
('Using separator ', '~', ' to split the string.')
('Using separator ~ to split the string.', '', '')
 

Python String split() Example

Python str.split(sep=None, maxsplit=- 1) returns a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done and the list will have at most maxsplit+1 elements. If maxsplit is not specified or -1, then there is no limit on the number of splits and all possible splits are made.

Let's have a look to below examples of split() function.

  • split() without sep and maxsplit values
  • If sep is not specified or is None, than consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

       
    # split method without arguments
    my_str_1 = " 4 3 2 1 10 "
    op_1 = my_str_1.split()
    print(op_1)
    
    
    my_str_2 = " 4 3    2 1 10 "
    op_2 = my_str_2.split()
    print(op_2)     
    
         
    Output
       
    ['4', '3', '2', '1', '10']
    ['4', '3', '2', '1', '10']
         

  • split() with sep argument
  • If sep is specified, than consecutive delimiters are not grouped together and empty strings would be delimited. sep argument may consist of multiple characters.

       
    # split method with sep argument
    my_str_1 = "orange, apple, fruits, , vegetables"
    op_1 = my_str_1.split(sep=",")
    print(op_1)
    
    # sep argument with multiple characters
    my_str_2 = "orange || apple || fruits ||   || vegetables"
    op_2 = my_str_2.split(sep="||")
    print(op_2)   
    
         
    Output
       
    ['orange', ' apple', ' fruits', ' ', ' vegetables']
    ['orange ', ' apple ', ' fruits ', '   ', ' vegetables']
         

  • split() with maxsplit argument
  • If maxsplit argument is specified, at most maxsplit splits are done and the output list will have at most maxsplit+1 elements .

       
    # split method with maxsplit argument
    my_str_1 = "orange ~ apple ~ fruits ~ grapes ~vegetables"
    op_1 = my_str_1.split(sep="~" , maxsplit=2)
    print(op_1)
           
    
         
    Output
       
    ['orange ', ' apple ', ' fruits ~ grapes ~vegetables']
         


Python String swapcase() Example

Python str.swapcase() returns copy of the string with uppercase characters converted to lowercase and vice versa.

   
# swapcase method example
my_str = "lowercase UPPERCASE"
op = my_str.swapcase()

print(op)
 

Output

   
LOWERCASE uppercase