Python căn bản (7): Python Strings

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ệ

Python căn bản (6): Python Numbers

Bài trước: Python căn bản (5): Data Types

-----

[Từ điển]

6. Python Numbers

6.1 Numeric types in Python

There are three numeric types in Python: int, float and complex

Variables of numeric types are created when you assign a value to them.

To verify the type of any object in Python, use the type() function.

Example:

x = 1    # int

y = 2.8  # float

z = 1j   # complex

print(type(x))

print(type(y))

print(type(z))

Int

Int, or integer, is a whole number, positive or negative,

without decimals, of unlimited length.

Example

x = 1

y = 35656222554887711

z = -3255522


print(type(x))

print(type(y))

print(type(z))

Float

Float, or "floating point number" is a number, positive or negative,

containing one or more decimals.

Example

x = 1.10

y = 1.0

z = -35.59


print(type(x))

print(type(y))

print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

Example

x = 35e3

y = 12E4

z = -87.7e100


print(type(x))

print(type(y))

print(type(z))

Complex

Complex numbers are written with a "j" as the imaginary part.

Example

x = 3+5j

y = 5j

z = -5j


print(type(x))

print(type(y))

print(type(z))

6.2 Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods.

Example

x = 1    # int

y = 2.8  # float

z = 1j   # complex


#convert from int to float:

a = float(x)


#convert from float to int:

b = int(y)


#convert from int to complex:

c = complex(x)


print(a)

print(b)

print(c)


print(type(a))

print(type(b))

print(type(c))

Note: You cannot convert complex numbers into another number type.

6.3 Random Number

Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers.

Example

Import the random module, and display a random number between 1 and 9:

import random


print(random.randrange(1,10))

6.4 Python Casting

Specify a Variable Type

There may be times when you want to specify a type on a variable. This can be done with casting. Python is an object-oriented language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)

float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)

str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

Example

Integers:

x = int(1)   # x will be 1

y = int(2.8) # y will be 2

z = int("3") # z will be 3


print(x)

print(y)

print(z)

Floats:

x = float(1)     # x will be 1.0

y = float(2.8)   # y will be 2.8

z = float("3")   # z will be 3.0

w = float("4.2") # w will be 4.2


print(x)

print(y)

print(z)

print(w)

Strings:

x = str("s1") # x will be 's1'

y = str(2)    # y will be '2'

z = str(3.0)  # z will be '3.0'


print(x)

print(y)

print(z)

6.5 Exercise

1. Which is NOT a legal numeric data type in Python?

A. int

B. long

C. float

D. complex

2. What will be the result of the following code:

print(int(35.88))

A. 35

B. 35.00

C. 36

D. 35.88

3. What will be the result of the following code:

print(float(35))

A. 35

B. 35.0

C. ‘35’

D. 0.35

4. Write a Python program that allows user input two numbers, then calculate the product and sum of two numbers.

Input:

Number 1:3

Number 2:4

Expected output:

Product: 12

Sum: 7

5. Write a Python program that allows user input the length and width of the rectangle, then calculate the perimeter and area of the rectangle.

Input:

Length:2.5

Width 3.0

Expected output:

Perimeter: 11.0

Area: 7.5

----- 

Cập nhật: 27/9/2024

Bài sau: Python căn bản (7): Python Strings

-----

[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ệ