Container Data Structures

String Methods

Using the upper() method, it is possible to convert and entire string to upper case:

course = " Introduction to Programming "

print(course.upper())
print(course)

 Output: INTRODUCTION TO PROGRAMMING 

Similarly, the lower() method converts the string to lower case:

course = " Introduction to Programming "

print(course.lower())
print(course)

 Output: introduction to programming 

When converting the strings, python uses default encoding, however, in some languages such as Turkish converting I to lower case has a different representation, ı, and the uppercase counterpart of i is İ instead of I. This requires usage of other character sets, code pages, or locale and the details are beyond the scope of this section.

The strip() method is used for removing the white space characters from the beginning and end of the string:

course = " \n         Introduction to Programming \n "
print("------------------------------------")
print(course)
print("------------------------------------")
course_cleared = course.strip()
print(course_cleared)
print("------------------------------------")

producing the following output:

------------------------------------
 
         Introduction to Programming 
 
------------------------------------
Introduction to Programming
------------------------------------

Substrings and single characters inside a string can be replaced by the replace() method:

course = " Introduction to Programming with C/C++ "
print(course)
print(course.replace("C/C++", "Java"))

#print(course.replace("Java", "Python"))
#java_course = course.replace("C/C++", "Java")
#print(java_course.replace("Java", "Python"))
#print(course.replace("C/C++", "Python"))

The split() method can be used to obtain a list of substrings by separating the original list by a specific substring:

course = " Introduction to Programming with Python "
print(course)
print(course.split(" "))
print(course.strip().split(" "))

print(course.split("to"))

course_list = [" Introduction to Programming with Python ", " Introduction to Programming with Java ", " Introduction to Programming with C/C++ "]

for course_name in course_list:
    print(course_name.split("with")[1])

for course_name in course_list:
    print(course_name.split("with ")[1])

Output:

 Introduction to Programming with Python 
['', 'Introduction', 'to', 'Programming', 'with', 'Python', '']
['Introduction', 'to', 'Programming', 'with', 'Python']
[' Introduction ', ' Programming with Python ']
 Python 
 Java 
 C/C++ 
Python 
Java 
C/C++ 

The methods do not modify the original string, but they may return a new string or a list of substrings instead.

email_address = 'monty@python.org'
user_name, domain = email_address.split('@')
print("Username:", user_name)
print("Domain:  ", domain)
print("E-mail:  ", email_address)

The list of string methods for Python3 is provided at https://docs.python.org/3/library/stdtypes.html#string-methods and other resources in the web.