Python căn bản (8): Python Strings (cont.)

Bài trước: Python căn bản (7): Python Strings

[Từ điển]

-----

8. Python Strings (cont.)

8.1 Modify Strings

Python has a set of built-in methods that you can use on strings.

Upper Case

The upper() method returns the string in upper case.

Example

a = "Van Teo"

print(a.upper())

Lower Case

The lower() method returns the string in lower case.

Example

a = "Van Teo"

print(a.lower())

Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often you want to remove this space.

The strip() method removes any whitespace from the beginning or the end.

Example

a = " Hello, World! "

print(a.strip()) # returns "Hello, World!"

Replace String

The replace() method replaces a string with another string.

Example

a = "Hello, World!"

print(a.replace("H", "J")) #Jello World!

Split String

The split() method returns a list where the text between the specified separator becomes the list items.

The split() method splits the string into substrings if it finds instances of the separator.

Example

a = "Hello, World!"

print(a.split(",")) # returns ['Hello', 'World!']

8.2 Concatenate Strings

To concatenate, or combine, two strings you can use the + operator.

Example

Merge variable a with variable b into variable c:

a = "Hello"

b = "World"

c = a + b

print(c)

Example

To add a space between them, add a " ":

a = "Hello"

b = "World"

c = a + " " + b

print(c)

8.3 Format Strings

As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:

age = 15

txt = "My name is Teo, I am " + age

print(txt)

But we can combine strings and numbers by using f-strings or the format() method!

F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations.

Example:

age = 15

txt = f"My name is Teo, I am {age}"

print(txt)

Placeholders and Modifiers

A placeholder can contain variables, operations, functions, and modifiers to format the value.

Example

Add a placeholder for the price variable

price = 59

txt = f"The price is {price} dollars"

print(txt)

A placeholder can include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals:

Example

Display the price with 2 decimals:

price = 59

txt = f"The price is {price:.2f} dollars"

print(txt)

A placeholder can contain Python code, like math operations.

Example

Perform a math operation in the placeholder, and return the result:

txt = f"The price is {20 * 59} dollars"

print(txt)

8.4 Escape Characters

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double quotes:

Example

You will get an error if you use double quotes inside a string that is surrounded by double quotes:

txt = "Hoc la mot cach "dau tu" cho tuong lai!"

print(txt)

To fix this problem, use the escape character \":

txt = "Hoc la mot cach \"dau tu\" cho tuong lai!"

print(txt)

Other escape characters used in Python:

Code  Result

\'          Single Quote           

\\          Backslash    

\n         New Line      

\r          Carriage Return      

\t          Tab    

\b         Backspace   

\f          Form Feed    

\ooo    Octal value   

\xhh    Hex value

8.5 String methods

Python has a set of built-in methods that you can use on strings. Note: All string methods return new values. They do not change the original string. Method Description capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string format_map() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isascii() Returns True if all characters in the string are ascii characters isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable to the end of the string ljust() Returns a left justified version of the string lower() Converts a string into lower case lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts replace() Returns a string where a specified value is replaced with a specified value rfind() Searches the string for a specified value and returns the last position of where it was found rindex() Searches the string for a specified value and returns the last position of where it was found rjust() Returns a right justified version of the string rpartition() Returns a tuple where the string is parted into three parts rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value strip() Returns a trimmed version of the string swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning

8.6. Exercise

1. What is the correct syntax to print a string in upper case letters? A. 'Welcome'.upper() B. 'Welcome'.toUpper() C. 'Welcome'.toUpperCase() D. 'Welcome'.setUpper() 2. Return the string without any whitespace at the beginning or the end. txt = " Hello World " x = _______ A. txt.split() B. txt.strip() C. txt.trim() D. trim(txt) 3. What is the correct syntax to merge variable x and y into variable z? A. z = x, y B. z = x = y C. z = x + y D. z = x * y 4. What will be the result of the following code: x = 'Welcome' y = 'Coders' print(x + y) A. Welcome Coders B. WelcomeCoders C. Welcome Coders D. Welcome+Coders 5. If x = 9, what is the correct syntax to print 'The price is 9.00 dollars'? A. print(f'The price is {x:.2f} dollars') B. print(f'The price is {x:2} dollars') C. print(f'The price is {x:format(2)} dollars') D. print(“The price is {x:format(2)} dollars”) 6. Write a program to input two strings, s1 and s2 from the keyboard, then create a new string s3 by appending s2 in the middle of s1. Input: s1: abcd s2: ef Expected output: abefcd ----- The answer hints: 1(A), 2(B), 3(C), 4(B), 5(A) 6. Given two strings, s1 and s2. Write a program to create a new string s3 by appending s2 in the middle of s1. #input s1 s1 = input("s1:") #input s2 s2 = input("s2:") #middle index number of s1 mi = int(len(s1)/2) #get character from 0 to the middle index number from s1 s3 = s1[:mi] #concatenate s2 to s3 s3 = s3 + s2 #append remaining character from s1 s3 = s3 + s1[mi:] print(f"s3:{s3}")
-----

Cập nhật: 3/10/2024

Bài sau: Python căn bản (9): Python Booleans

-----

[Nội dung tham khảo từ w3schools, pynative và Internet]

Bạn muốn học Python căn bản tại Đà Lạt, liên hệ