An Introduction to the Art of Computer Programming Using Python in the Age of Generative AI

III. Strings and Text Data

Introduction to Strings

Strings are a sequence of characters and are an essential data type in any programming language. In Python, strings are immutable, meaning that they cannot be changed after they are created. This chapter explores the various aspects of strings in Python, including their creation, manipulation, and some common operations performed on them.

Creating Strings

Strings in Python can be enclosed in single ('string') or double ("string") quotes. "255" denotes a string, not the integer 255. We can also use the + and * operators on strings.


greeting = 'Hello, World!'
print(greeting)

sentence = "It's a beautiful day!"
print(greeting + ' ' + sentence)
print(3 * (greeting + ' '))
print(greeting * sentence)
        

Accessing and Slicing Strings

You can access individual characters in a string using indexing, and a range of characters in a string using slicing. Strings are immutable.


my_string = 'Hello, World!'
print(len(my_string))
print(my_string[0])
print(my_string[7:12])
my_string[0] = 'B'
        

Common String Operations

Python provides a wide range of built-in methods for performing common string operations, such as whitespace trimming, substring searching, and string splitting.


my_string = ' Hello, World! '
print(my_string.lower())
print(my_string.upper())
print(my_string.strip())
print(my_string.replace('World', 'Python'))
print(my_string.split(','))
        

Formatting Strings

Python 3.6 introduced f-strings, a way to embed expressions in string literals. You can use f-strings to embed variables, expressions, and function calls in strings.


name = 'World'
print(f'Hello, {name}!')
        

Handling Unicode

Unicode is a standard for encoding a wide variety of characters from many different writing systems. Python strings are Unicode by default, allowing characters from almost any written language to be represented.


unicode_string = 'שלום עולם'
print(unicode_string)
        
Back to Home