Bài trước: Python căn bản (6): Python Numbers
-----
[Từ điển]
7. Python Strings
7.1 String Basics
Strings in python are surrounded by either single quotation marks,
or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function
Example:
print("Hello")
print('Hello')
Quotes Inside Quotes
You can use quotes inside a string, as long as they don't match
the quotes surrounding the string.
Example:
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Assign String to a Variable
Assigning a string to a variable is done with the variable name
followed by an equal sign and the string
Example:
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three
quotes.
Example:
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Or three single quotes:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same
position as in the code.
7.2 Strings Are Arrays
Like many other popular programming languages, strings in Python
are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single
character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character
has the position 0).
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a
string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
String Length
To get the length of a string, use the len()
function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string,
we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is
present.")
Check if NOT
To check if a certain phrase or character is NOT present in a
string, we can use the keyword not
in.
Example
Check if "expensive" is NOT present in the following
text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement.
Example
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is
NOT present.")
7.3 Slicing Strings
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon,
to return a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Note: The first character has index 0.
Slice From the Start
By leaving out the start index, the range will start at the first
character.
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Slice To the End
By leaving out the end index, the range will go to the end.
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string.
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!"
(position -2):
b = "Hello, World!"
print(b[-5:-2])
7.4 Exercise
1. What will be the result of the following code:
x = 'Welcome'
print(x[3])
A. Wel
B. l
C. c
D. Welcome Welcome Welcome
2. What will be the result of the following code:
x = 'Welcome'
print(x[3:5])
A. lcome
B. come
C. com
D. co
3. txt = "Hello World". Get the characters from index 2
to index 4 (llo)
A. x = txt[2:5]
B. x = txt[2:]
C. x = txt[:5]
D. x = txt[2:4]
4. What will be the result of the following code:
x = 'Welcome'
print(x[3:])
A. lcome
B. come
C. com
D. co
5. Write a Python code to remove characters of a string from 0
to n and return a new string. With string and n will be input by user (n <
length of string).
Input:
Nhap mot chuoi: hi bac Teo
So ki tu can xoa: 6
Expected Output:
hi bac
6. Write a program to create a new string made of an input
string’s first, middle, and last character.
Input:
Nhap vao chuoi:vanteo
Expected Output:
Chuoi ket qua: vto
7. Write a program to create a new string made of the middle three
characters of an input string.
Input 1:
Nhap vao chuoi:vanteo
Expected Output 1:
Chuoi ket qua: nte
Input 2:
Nhap vao chuoi:vangteo
Expected Output 2:
Chuoi ket qua: ngt
-----
The answer hints:
1(C),
2(D), 3(A), 4(B)
5. Write a Python code to remove characters of a string from 0 to n
and return a new string. With string and n will be input by user (n < length
of string).
str = input("Nhap mot chuoi: ")
n = int(input("So ki tu can xoa: "))
kq = str[0:n]
print(kq)
6. Write a program to create a new string made of an input
string’s first, middle, and last character.
str1 = input("Nhap vao chuoi:")
# Get first character
result = str1[0]
# Get string size
l = len(str1)
# Get middle index number
mi = int(l / 2)
# Get middle character and add it to result
result = result + str1[mi]
# Get last character and add it to result
result = result + str1[l - 1]
print("Chuoi ket qua:", result)
7. Write a program to create a new string made of the middle three
characters of an input string.
str1 = input("Nhap vao chuoi:")
#get middle index number
mi = int(len(str1) / 2)
# use string slicing to get result characters
res = str1[mi - 1:mi + 2]
print("Ket qua:", res)
-----
Cập nhật: 30/9/2024
Bài sau: Python căn bản (8): Python Strings (cont.)
-----
[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ệ