Hướng dẫn is number or string in python? - là số hay chuỗi trong python?

Phương thức chuỗi


Thí dụ

Kiểm tra xem tất cả các ký tự trong văn bản là số:

TXT = "565543"

x = txt.isnumeric ()

in (x)

Hãy tự mình thử »


Định nghĩa và cách sử dụng

Phương thức

Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
0 trả về đúng nếu tất cả các ký tự là số (0-9), nếu không thì sai.

Số mũ, như ² và ¾ cũng được coi là giá trị số.

Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
1 và
Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
2 không được coi là giá trị số, bởi vì tất cả các ký tự trong chuỗi phải là số và
Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
3 và
Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
4 thì không.


Cú pháp

Giá trị tham số

Không có tham số.


Nhiều ví dụ hơn

Thí dụ

Kiểm tra xem các ký tự có phải là số không:

a = "\ u0030" #Unicode cho 0b = "\ u00b2" #Unicode for & sup2; C = "10km2" d = "-1" e = "1,5"
b = "\u00B2" #unicode for ²
c = "10km2"
d = "-1"
e = "1.5"

in (a.isnumeric ()) in (b.isnumeric ()) in (c.isNumeric ()) in (d.isNumeric ()) in (e.isNumeric ())
print(b.isnumeric())
print(c.isnumeric())
print(d.isnumeric())
print(e.isnumeric())

Hãy tự mình thử »


Phương thức chuỗi


Trong bài học này, bạn sẽ học cách kiểm tra đầu vào của người dùng là một số hoặc chuỗi trong Python. Chúng tôi cũng sẽ đề cập đến cách chấp nhận số làm đầu vào từ người dùng. Khi chúng ta nói một số, nó có nghĩa là nó có thể là số nguyên hoặc nổi.

Hiểu đầu vào của người dùng

Python 3 có đầu vào hàm tích hợp () để chấp nhận đầu vào của người dùng. Nhưng nó không đánh giá dữ liệu nhận được từ hàm

Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
5, tức là, hàm
Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
5 luôn chuyển đổi đầu vào của người dùng thành một chuỗi và sau đó trả lại cho chương trình gọi.

Hướng dẫn is number or string in python? - là số hay chuỗi trong python?
Kiểm tra đầu vào là một số hoặc một chuỗi trong Python

Hãy cho chúng tôi hiểu điều này với một ví dụ.

number1 = input("Enter number and hit enter ")
print("Printing type of input value")
print("type of number ", type(number1))
Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'

Như bạn có thể thấy, đầu ra hiển thị loại biến dưới dạng chuỗi (STR).

Giải pháp: Trong tình huống như vậy, chúng ta cần chuyển đổi đầu vào của người dùng một cách rõ ràng thành số nguyên và nổi để kiểm tra xem nó có một số không. Nếu chuỗi đầu vào là một số, nó sẽ được chuyển đổi thành int hoặc float mà không có ngoại lệ.: In such a situation, We need to convert user input explicitly to integer and float to check if it’s a number. If the input string is a number, It will get converted to int or float without exception.

Chuyển đổi đầu vào chuỗi thành int hoặc float để kiểm tra xem nó có phải là số không

Cách kiểm tra xem đầu vào là số hoặc chuỗi trong Python

  1. Chấp nhận đầu vào từ người dùng

    Sử dụng chức năng

    Output
    Enter number and hit enter 10
    Printing type of input value
    type of number class 'str'
    5 để chấp nhận đầu vào từ người dùng

  2. Chuyển đổi đầu vào thành số nguyên

    Để kiểm tra xem chuỗi đầu vào có phải là số nguyên hay không, hãy chuyển đổi đầu vào của người dùng thành loại số nguyên bằng hàm tạo

    Output
    Enter number and hit enter 10
    Printing type of input value
    type of number class 'str'
    8.

  3. Chuyển đổi đầu vào thành số float

    Để kiểm tra xem đầu vào có phải là số float hay không, hãy chuyển đổi đầu vào của người dùng thành loại float bằng hàm tạo

    Output
    Enter number and hit enter 10
    Printing type of input value
    type of number class 'str'
    9.

  4. Xác nhận kết quả

    Nếu đầu vào là số nguyên hoặc số float, nó có thể được chuyển đổi thành công thành loại

    def check_user_input(input):
        try:
            # Convert it into integer
            val = int(input)
            print("Input is an integer number. Number = ", val)
        except ValueError:
            try:
                # Convert it into float
                val = float(input)
                print("Input is a float  number. Number = ", val)
            except ValueError:
                print("No.. input is not a number. It's a string")
    
    
    input1 = input("Enter your Age ")
    check_user_input(input1)
    
    input2 = input("Enter any number ")
    check_user_input(input2)
    
    input2 = input("Enter the last number ")
    check_user_input(input2)
    0 hoặc
    def check_user_input(input):
        try:
            # Convert it into integer
            val = int(input)
            print("Input is an integer number. Number = ", val)
        except ValueError:
            try:
                # Convert it into float
                val = float(input)
                print("Input is a float  number. Number = ", val)
            except ValueError:
                print("No.. input is not a number. It's a string")
    
    
    input1 = input("Enter your Age ")
    check_user_input(input1)
    
    input2 = input("Enter any number ")
    check_user_input(input2)
    
    input2 = input("Enter the last number ")
    check_user_input(input2)
    1. Khác, chúng ta có thể kết luận nó là một chuỗi

Lưu ý: Nếu đầu vào là số nguyên hoặc số float, nó có thể được chuyển đổi thành công thành int hoặc float và bạn có thể kết luận rằng đầu vào đã nhập là một số. Mặt khác, bạn có ngoại lệ

def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)
2, có nghĩa là đầu vào người dùng đã nhập là một chuỗi.: If an input is an integer or float number, it can successfully get converted to int or float, and you can conclude that entered input is a number. Otherwise, You get a
def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)
2 exception, which means the entered user input is a string.

Chương trình : :

def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)
Output

Enter your Age 28
Input is an integer number. Number =  28

Enter any number 3.14
Input is a float  number. Number =  3.14

Enter the last number 28Jessa
No.. input is not a number. It's a string
  • Như bạn có thể thấy ở đầu ra ở trên, người dùng đã nhập 28 và nó được chuyển đổi thành loại số nguyên mà không có ngoại lệ.
  • Ngoài ra, khi người dùng nhập 3.14 và nó được chuyển đổi thành loại float mà không có ngoại lệ.
  • Nhưng khi người dùng nhập một số với một số ký tự trong đó (28Jessa), Python đã tăng ngoại lệ
    def check_user_input(input):
        try:
            # Convert it into integer
            val = int(input)
            print("Input is an integer number. Number = ", val)
        except ValueError:
            try:
                # Convert it into float
                val = float(input)
                print("Input is a float  number. Number = ", val)
            except ValueError:
                print("No.. input is not a number. It's a string")
    
    
    input1 = input("Enter your Age ")
    check_user_input(input1)
    
    input2 = input("Enter any number ")
    check_user_input(input2)
    
    input2 = input("Enter the last number ")
    check_user_input(input2)
    3 vì nó không phải là int.

Sử dụng Chuỗi def check_user_input(input): try: # Convert it into integer val = int(input) print("Input is an integer number. Number = ", val) except ValueError: try: # Convert it into float val = float(input) print("Input is a float number. Number = ", val) except ValueError: print("No.. input is not a number. It's a string") input1 = input("Enter your Age ") check_user_input(input1) input2 = input("Enter any number ") check_user_input(input2) input2 = input("Enter the last number ") check_user_input(input2)4 Phương thức để kiểm tra đầu vào của người dùng là số hoặc chuỗi

Lưu ý: Hàm

def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)
4 sẽ chỉ hoạt động cho các số nguyên dương. tức là, nếu bạn vượt qua bất kỳ số float nào, nó sẽ không hoạt động. Vì vậy, tốt hơn là sử dụng phương pháp đầu tiên.: The
def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)
4 function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.

Hãy để thực hiện chương trình để xác nhận điều này.

def check_is_digit(input_str):
    if input_str.strip().isdigit():
        print("User input is Number")
    else:
        print("User input is string")


num1 = input("Enter number and hit enter")
check_is_digit(num1)

num2 = input("Enter number and hit enter")
check_is_digit(num2)
Output

Enter number and hit enter 45
User input is Number

Enter number and hit enter 45Jessa
User input is string

Ngoài ra, nếu bạn có thể kiểm tra xem biến Python có phải là số hoặc chuỗi hay không, hãy sử dụng hàm

def check_user_input(input):
    try:
        # Convert it into integer
        val = int(input)
        print("Input is an integer number. Number = ", val)
    except ValueError:
        try:
            # Convert it into float
            val = float(input)
            print("Input is a float  number. Number = ", val)
        except ValueError:
            print("No.. input is not a number. It's a string")


input1 = input("Enter your Age ")
check_user_input(input1)

input2 = input("Enter any number ")
check_user_input(input2)

input2 = input("Enter the last number ")
check_user_input(input2)
6.

Thí dụ

num = 25.75
print(isinstance(num, (int, float)))
# Output True

num = '28Jessa'
print(isinstance(num, (int, float)))
# Output False

Chỉ chấp nhận một số làm đầu vàoaccept a number as input

Hãy để viết một chương trình đơn giản bằng Python để chỉ chấp nhận các số đầu vào từ người dùng. Chương trình sẽ chỉ dừng lại khi người dùng nhập số đầu vào.

while True:
    num = input("Please enter a number ")
    try:
        val = int(num)
        print("Input is an integer number.")
        print("Input number is: ", val)
        break;
    except ValueError:
        try:
            float(num)
            print("Input is an float number.")
            print("Input number is: ", val)
            break;
        except ValueError:
            print("This is not a number. Please enter a valid number")
Output

Please enter a number 28Jessa
This is not a number. Please enter a valid number

Please enter a number 28
Input is an integer number.
Input number is:  28

Vấn đề thực hành: Kiểm tra đầu vào của người dùng là số dương hoặc âm

Hiển thị giải pháp

user_number = input("Enter your number ")

print("\n")
try:
    val = int(user_number)
    if val > 0:
        print("User number is positive ")
    else:
        print("User number is negative ")
except ValueError:
    print("No.. input string is not a number. It's a string")

Bước tiếp theo

Hãy cho tôi biết ý kiến ​​và phản hồi của bạn trong phần dưới đây.

Ngoài ra, giải quyết:

  • Bài tập đầu vào và đầu ra của Python
  • Đầu vào Python và bài kiểm tra đầu ra
  • Bài tập Python cho người mới bắt đầu
  • Câu đố Python cho người mới bắt đầu

Bài tập và câu đố Python

Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.

  • Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
  • Mỗi bài tập chứa 10 câu hỏi
  • Mỗi bài kiểm tra chứa 12-15 mcq

Python là một chuỗi hay số nguyên?

Python cung cấp phương thức isnumeric () kiểm tra xem một chuỗi có phải là số nguyên hay không.Phương pháp này tương tự như phương thức isDigit () nhưng với một vài khác biệt.Phương thức isNumeric () kiểm tra xem tất cả các ký tự trong chuỗi là số.Trong khi phương thức isDigit () kiểm tra xem các chuỗi chỉ chứa các chữ số.isnumeric() method that checks whether a string is an integer or not. This method is similar to the isdigit() method but with a few differences. The isnumeric() method checks whether all the characters in the string are numeric. While the isdigit() method checks whether the strings contain only digits.

%D và %s trong Python là gì?

%s hoạt động một trình giữ chỗ cho một chuỗi trong khi %D hoạt động như một trình giữ chỗ cho một số.Các giá trị liên quan của chúng được truyền qua thông qua một tuple bằng toán tử %.. Their associated values are passed in via a tuple using the % operator.