Python Strings

Introduction to Strings

In Python, strings can be enclosed in either single quotes or double quotes. For example, 'book' and "book" are equivalent.

To print a string literal, you can use the print() function:

print("The Great Gatsby")
print('The Great Gatsby')

Expected Output:

The Great Gatsby
The Great Gatsby

Official Documentation: Strings in Python

Using Quotes Within Strings

Quotes can be included inside a string as long as they don’t match the surrounding quotes:

print("It's a good book")
print("He said 'Read more books'")
print('She replied "Books are amazing"')

Expected Output:

It's a good book
He said 'Read more books'
She replied "Books are amazing"

Official Documentation: Quotes in Strings

Assigning Strings to Variables

To assign a string to a variable, use the variable name followed by an equal sign and the string:

favorite_book = "1984"
print(favorite_book)

Expected Output:

1984

Official Documentation: Assigning Strings

Multiline Strings

To create a multiline string, use triple quotes. You can use either triple double quotes or triple single quotes:

book_description = """1984 is a dystopian social science fiction novel
and cautionary tale, written by the English writer George Orwell."""
print(book_description)
book_description = '''1984 is a dystopian social science fiction novel
and cautionary tale, written by the English writer George Orwell.'''
print(book_description)

Note that line breaks in the output will match those in the code.

Expected Output:

1984 is a dystopian social science fiction novel
and cautionary tale, written by the English writer George Orwell.

Official Documentation: Multiline Strings

Strings as Arrays

Strings in Python are essentially arrays of bytes representing Unicode characters. Unlike some languages, Python does not have a distinct character type; a single character is just a string of length 1. You can access individual characters using square brackets:

book_title = "The Catcher in the Rye"
print(book_title[4])

Expected Output:

C

Official Documentation: Strings as Arrays

Looping Through a String

Since strings are iterable, you can loop through each character using a for loop:

for letter in "Moby Dick":
    print(letter)

Expected Output:

M
o
b
y

D
i
c
k

Official Documentation: Looping Through Strings

Getting String Length

To find the length of a string, use the len() function:

book_title = "Pride and Prejudice"
print(len(book_title))

Expected Output:

19

Official Documentation: len()

Checking for Substrings

To check if a substring exists within a string, use the in keyword:

quote = "The pen is mightier than the sword."
print("pen" in quote)

Expected Output:

True

You can use this in an if statement as well:

if "pen" in quote:
    print("Yes, 'pen' is present.")

Expected Output:

Yes, 'pen' is present.

Official Documentation: Checking for Substrings

Checking for Absence

To check if a substring is not present in a string, use the not in keyword:

quote = "The pen is mightier than the sword."
print("book" not in quote)

Expected Output:

True

It can also be used in an if statement:

if "book" not in quote:
    print("No, 'book' is NOT present.")

Expected Output:

No, 'book' is NOT present.

Official Documentation: Checking for Absence

String Slicing

Strings can be sliced to obtain a range of characters. Use the slice syntax with start and end indices:

book_title = "To Kill a Mockingbird"
print(book_title[3:7])

Expected Output:

Kill

If you omit the start index, slicing will start from the beginning of the string:

print(book_title[:2])

Expected Output:

To

Official Documentation: String Slicing

Modifying Strings

Python offers several methods to modify strings:

Upper Case

book_title = "To Kill a Mockingbird"
print(book_title.upper())

Expected Output:

TO KILL A MOCKINGBIRD

Lower Case

book_title = "To Kill a Mockingbird"
print(book_title.lower())

Expected Output:

to kill a mockingbird

Removing Whitespace

Use strip() to remove whitespace from the start and end of a string:

book_title = "  War and Peace  "
print(book_title.strip())

Expected Output:

War and Peace

Official Documentation: String Modifying Methods

String Concatenation

To concatenate strings, use the + operator:

book_title1 = "Pride"
book_title2 = "Prejudice"
full_title = book_title1 + " and " + book_title2
print(full_title)

Expected Output:

Pride and Prejudice

Official Documentation: String Concatenation

String Formatting

To combine strings with numbers, use f-strings or the format() method:

F-Strings

book_count = 5
txt = f"I have {book_count} books."
print(txt)

Expected Output:

I have 5 books.

Format Method

price = 19.99
txt = "The price of the book is {:.2f} dollars".format(price)
print(txt)

Expected Output:

The price of the book is 19.99 dollars

Official Documentation: String Formatting

Leave a Comment

那麼,僱主可否自行申請外傭,自行辦理 direct hire 的手續呢 ?.