Str & Int data type

本文介绍了Python中的字符串(str)和整数(int)类型。字符串是字符序列,不可变,可以通过索引访问其字符;整数可以是正负整数,并支持不同基数的表示,如二进制、八进制和十六进制。文章通过示例展示了如何创建、访问和操作这两种数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Str data type

In Python, a string is a sequence of characters enclosed within a single quote or double quote. These characters could be anything like letters, numbers, or special symbols enclosed within double quotation marks. For example, "Python" is a string.

The string type in Python is represented using a str class.

To work with text or characters data in Python, we use strings. Once a string is created, we can do many operations on it. Such as searching inside it, creating a substring from it, and spliting it.

Example:

str = "Python"
print(type(str)) # <class 'str'>

# display string
print(str) # 'Python'

# accessing 2nd character of a string
print(str[1]) # y

Note: The string is immutable, i.e. it can not be changed once defined. You need to create a copy of it if you want to modify it. This non-changeable behavior is called immutability.

Example:

str = 'python'
# Now let's try to change 2nd character of a string
str[0] = 'P'
# Gives TypeError: 'str' object does not support item assignment

Int data type

Python uses the int data type to represent whole integer values. For example, we can use the int data type to store the roll number of a student. The integer type in Python is represented using a int class.

You can store positive and negative interger numbers of any length such as 1, -10, 31431.

We can create an integer variable using the two ways.

  1. Directly assigning an integer value to a variable
  2. Using a int() class. 

Example:

# store int value
int_number = 10

# display int_number
print("int_number is:", int_number) # output 10

# display int_number type
print(type(int_number) # output class 'int'

# store integer using int() class
id = int(25)
print(id) # 25
print(type(id)) # class 'int'

You can also store integer values other than base 10 such as:

  1. Binary(base 2)
  2. Octal (base 3)
  3. Hexadecimal numbers (base 16)
# decimal int 16 with base 8
# prefix with zero + letter b
octal_num = 0o20
print(octal_num) # 16
print(type(octal_num)) # class 'int'

# decimal int 16 with base 16
# prefix with zero + letter x
hexadecimal_num = 0x10 # decimal equivalent of 21
print(hexadecimal_num) # 16
print(type(hexadecimal_num)) # class 'int'

# decimal int 16 with base 2
# prefix with zero + letter b
binary_num = 0b10000 # decimal equivalent of 6
print(binary_num) # 16
print(type(binary_num)) # class 'int'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值