Python - 基本数据类型及其常用的方法之数字与字符串

数字(int):

  1、int()(将字符串换为数字)

a = "123"
print(type(a), a)

b = int(a)
print(type(b), b)

num = "a"
# 使用 int 方法时默认转换为十进制数
# 通过base来指定转换后的类型
v = int(num, base=16)
print(v)

 输出:

<class ‘str‘> 123
<class ‘int‘> 123
10

  2、bit_length() (当前数字的二进制前面的零不算)

a1 = 2  # 0010
a2 = 3  # 0011
v1 = a1.bit_length()
v2 = a2.bit_length()
print(v1)
print(v2)

输出

2
2

字符串(str):

  1、capitalize()

test = "aiden"
# 首字母大写
v = test.capitalize()
print(v)

输出:

Aiden

  2、casefold() 和 lower() (转化大小写)

test = "aiDen"
v1 = test.casefold()
print(v1)

v2 = test.lower()
print(v2)

输出:

aiden
aiden

lower() 只针对英文的大小写;casefold() 可以转换很多未知的大小写对应关系

  3、center(); ljust(); rjust

test = "aiden"
# 设置宽度, 并将内容居中
# 20 代指总长度
# * 空白位置的填充(一个字符,包括中文),默认为空
v = test.center(20, "*")
print(v)

输出:

*******aiden********
test = "aiden"
v1 = test.ljust(20, "*")
v2 = test.rjust(20, "*")
print(v1)
print(v2)

输出:

aiden***************
***************aiden

  4、count()

test = "aidenaiden"
# 在字符串中查找子列的个数
# 2 表示从第 2 个开始;4 表示到第 3 个时结束(从零开始计数)
v1 = test.count("a")
v2 = test.count("de", 2, 4)
print(v1)
print(v2)

输出:

2
1

  5、encode()

  6、decode()

  7、endswith() 和 startwith()

test = "aidenaiden"
# 以什么开始(可设置开始和结束的参数)
v = test.startswith("ai", 0, 2 )
print(v)
# 以什么结尾(可设置开始和结束的参数)
v = test.endswith("d")
print(v)

输出:

True
False

  8、find()

# 从开始往后找,找到第一个后获取其位置(可设置开始和结束的参数)
test = "aidenaiden"
v = test.find("de",2, 4 )
print(v)

输出:

2

  9、formate() 和 formate_map()

# 格式化:将字符中的占位符替换为指定的值
test = "My name is {name},my age is {age}"
print(test)
v = test.format(name="Aiden", age=18)
print(v)

输出:

My name is {name},my age is {age}
My name is Aiden,my age is 18
# 格式化:将字符中的占位符替换为指定的值
# 可以指定位序(空则默认从零开始)
test = "My name is {0},my age is {1}"
print(test)
v = test.format("Aiden", 18)
print(v)

输出:

My name is {0},my age is {1}
My name is Aiden,my age is 18
# 传入的值为字典
test = "My name is {name},my age is {age}"
v = test.format_map({"name": "Aiden", "age": 18})
print(v)

输出:

My name is Aiden,my age is 18

  10、isalnum()

# 字符串中是否只包含数字和字母
test1 = "agfgdge123+-"
test2 = "aiden"
v1 = test1.isalnum()
v2 =test2.isalnum()
print(v1)
print(v2)

输出:

False
True

  11、expendtabs()

# 断句输出\t前的字符若不够则空格补齐(及字符串和\t长度相加为 10 遇到\n换行)
test = "name\tage\taddress\temail\naiden\t18\twenzhou\[email protected]\naiden\t18\twenzhou\[email protected]\n"
v = test.expandtabs(10)
print(v)

输出:

name      age       address   email
aiden     18        wenzhou   @qq.com
aiden     18        wenzhou   @qq.com

  12、isalpha()

# 判断字符串是否由字母组成(包括汉字)
test1 = "天fag"
test2 = "12afag"
v1 = test1.isalpha()
v2 = test2.isalpha()
print(v1)
print(v2)

输出:

True
False

  13、isdecimal(), isdigital(), isnumeric()

# 判断当前输入的是否是数字
test = "123"
v1 = test.isdecimal()
v2 = test.isdigit()
v3 = test.isnumeric()print(v1, v2, v3)

输出:

True True True

三个都能输出数字

# 判断当前输入的是否是数字
test = "123②"
v1 = test.isdecimal()
v2 = test.isdigit()
v3 = test.isnumeric()print(v1, v2, v3)

输出:

False True True

isdigit() 可以输出符号数字(②)

# 判断当前输入的是否是数字
test = "123②二"
v1 = test.isdecimal()
v2 = test.isdigit()
v3 = test.isnumeric()
print(v1, v2, v3)

输出:

False False True

isnumeric() 可以输出中文数字

  14、isprintable()

# 输出时是否有不可见的字符
test1 = "abcd"
test2 = "abc\td"
v1 = test1.isprintable()
v2 = test2.isprintable()
print(v1, v2)

输出:

True False

  15、isspace()

# 判断是否全部为空格
test1 = "ab cd"
test2 = "    "
v1 = test1.isspace()
v2 = test2.isspace()
print(v1, v2)

输出:

False True

  16、title() 和 istitle()

# istitle()判断是否为标题
# title()将每个字符串的首字母大写
test = "Return True if the string is a title-cased string, False otherwise."
v1 = test.istitle()
print(v1)
v2 = test.title()
print(v2)
v3 = v2.istitle()
print(v3)

输出:

False
Return True If The String Is A Title-Cased String, False Otherwise.
True

  17、join()(别的数据类型也可以用)

# 将字符串中的每一个元素按照指定的字符进行拼接
test = "或许爱你还能算一种天分"
print(test)
# t = " "
v = " ".join(test)
print(v)

输出:

或许爱你还能算一种天分
或 许 爱 你 还 能 算 一 种 天 分

  18、lower(), islower(); upper(), isupper()

test = "Aiden"
v1 = test.lower()
print(v1)
v1 = v1.islower()
print(v1)

输出

aiden
True
test = "Aiden"
v1 = test.upper()
print(v1)
v1 = v1.isupper()
print(v1)

输出:

AIDEN
True

  19、strip(), lstrip(), rstrip()

# 默认删除空白(空格,\t, \n)
# strip 删除两边
# lstrip 删除左边
# rstrip 删除右边
test = "\n Aiden \t"
v1 = test.strip()
v2 = test.lstrip()
v3 = test.rstrip()
print(v1)
print(v2)
print(v3)

输出:

AidenAiden 

     Aiden

也可以删除指定字符

# 移除指定字符
# 按照有限最多匹配
test = "xAiendenx"
v1 = test.strip("x")
v2 = test.lstrip("x")
v3 = test.rstrip("enxd")
print(v1)
print(v2)
print(v3)

输出:

AiendenAiendenxxAi

  20、maketrans() 和 translate()

# 将字符串按照对应关系替换
test1 = "aeiou"
test2 = "12345"
test = "asqwoeradurqoienuato"
# 设置对应关系
m = str.maketrans(test1, test2)
v = test.translate(m)
print(v)

输出:

1sqw42r1d5rq432n51t4

  21、partition() 和 rpartition()

# 只能将字符串按照指定的字符串分割成三份
test = "aidden"
v1 = test.partition("d")
v2 = test.rpartition("d")
print(v1)
print(v2)

输出:

(‘ai‘, ‘dd‘, ‘en‘)
(‘aid‘, ‘d‘, ‘en‘)

  22、split(), rsplit(), splitlines()

# 将字符串按照指定的字符串和指定的次数分隔
# 但不能获取指定的分割字符串
test = "adaidenda"
v1 = test.split("d", 2)
v2 = test.rsplit("d", 2)
print(v1)
print(v2)

输出:

[‘a‘, ‘ai‘, ‘enda‘]
[‘adai‘, ‘en‘, ‘a‘]
# 只根据换行符号分割
test = "ad\naiden\nda"
v1 = test.splitlines() # 默认False
v2 = test.splitlines(True)
print(v1)
print(v2)

输出:

[‘ad‘, ‘aiden‘, ‘da‘]
[‘ad\n‘, ‘aiden\n‘, ‘da‘]

  23、swapcase()

# 大小写装换
test = "Aiden"
v1 = test.swapcase()
print(v1)

输出:

AaIDEN

  24、replace()

# 将字符串中的字符替换为指定的字符
# 可指定替换的个数
test = "aidenaidenaiden"
v1 = test.replace("den", "b")
v2 = test.replace("den", "b", 2)
print(v1)
print(v2)

输出:

aibaibaib
aibaibaiden

  25、将数字转换为字符串

# 数字转换为字符串
s = 123
v = str(s)
print(v, type(v))

输出:

123 <class ‘str‘>

  26、列表转化成字符串

# 列表中只有字符串时
li = ["aiden", "nihao", "alix"]
v = "".join(li)  # join本质上使用for循环
print(v)

输出:

aidennihaoalix
# 列表中既有字符串又有数字时
# 需要自己写for循环
li = [123, "nihao", "alix"]
s = ""
for i in li:
    s += str(i)
print(s)

输出:

123nihaoalix

  27、其他(别的数据类型也可以用)

test = "aiden"
# 索引
print(test[0])
# 切片
print(test[0:2])  # >=0  <2
print(test[0:-1])
# for 循环
for i in test:
    print(i)

输出:

a
ai
aide
a
i
d
e
n

a
ai
ai

字符串一旦创建不可修改;一旦拼接或者修改都会重新生成字符串。

原文地址:https://www.cnblogs.com/Fu-yi/p/11619569.html

时间: 2024-08-30 13:12:13

Python - 基本数据类型及其常用的方法之数字与字符串的相关文章

Python - 基本数据类型及其常用的方法之元组

元组 特点:一级元素无法被修改,且不能被增加或者删除. 基本操作: tu = (11, 22, ["aiden", 33, ("qwe", 11)], 77) # 索引取值 print(tu[1]) # 切片取值 print(tu[2:4]) # for循环遍历(可迭代对象) for i in tu[0:3]: print(i) 输出: 22 (['aiden', 33, ('qwe', 11)], 77) 11 22 ['aiden', 33, ('qwe', 1

Python - 基本数据类型及其常用的方法之字典和布尔值

字典 特点:{"key1": value1, "key2":value2}  , 键值对中的值可以为任何数据类型,键不能为列表.字典(无法哈希),布尔值可以为键(0/1)但是可能会与其他的键重复:字典的存储是无序的. 基本操作: # 字典 info = { "k1": 18, 2: True, "k3": [11, 22, 33], "k4": {"kk1": "vv1&quo

Python - 基本数据类型及其常用的方法之列表

列表: 特点:用 [] 括起来,切元素用逗号分隔:列表内的元素可以为任何的数据类型. 列表的基本操作: 1.修改 li = [12, 5, 6, ["Aiden", [2, 4], "你好世界"], True] # 修改 print(li) # 通过索引修改值 li[1] = 99 print(li) # 通过切片修改值 li[0:3] = [1, 2, 3] print(li) 输出: [12, 5, 6, ['Aiden', [2, 4], '你好世界'], T

数据类型总结(一)(数字,字符串)

数据类型总结 数字 字符串 列表 元组 字典 按照存值个数: 1个:数字,字符串 多个:列表,元组,字典 按照可变不可变: 可变:列表,字典 不可变:数字,字符串,元组 按照访问方式: 直接访问:数字 索引:字符串,列表,元组==>序列类型seq 映射:字典 一.数字 特性:1.只能存放一个值2.一经定义,不可更改3.直接访问分类:整型,长整型(只有python2中才有),浮点,复数 整型int:年级,年纪,等级,身份证号,qq号,手机号level=10Python的整型相当于C中的long型,

基本数据类型的常用处理方法

可变类型:值改变,但id不变,证明就是改变原值,是可变类型 不可变类型:值改变,但是id也跟着变,证明就是在产生了新的值,是不可变类型 数字类型 整形int age = 10 #age=int(10) 浮点型float float("1.2") res = str([1,2,4]) # 转为字符串 常用操作+内置方法 1. 按索引值 2. 切片--msg[0:3:1] msg[-1:-12:-1] msg[::-1] 3. 长度--len() 4. strip()--";;e

python基本数据类型及常用功能

1.数字类型 int -int(将字符串转换为数字) a = "123" print(type(a),a) b = int(a) print(type(b),b) num = "0011" v = int(num,base=16) print(v) PS:type打印数据类型,base=16是把num以16进制格式打印出十进制结果. -bit_lenght(当前数字的二进制位数) age = 5 r = age.bit_length() print(r) PS:5的

Python图像处理库Pillow常用使用方法

PIL(Python Imaging Library)是Python一个强大方便的图像处理库,只支持到Python2.7.Pillow是PIL的一个派生分支,在Python3标准库中用Pillow代替PIL.Pillow官网:https://pillow.readthedocs.io/en/latest/handbook/index.html 下面是使用例子,用法可见代码注释. from PIL import Image,ImageFilter,ImageGrab,ImageDraw,Image

Python基础课:列表常用的方法

lst.append(x)   | 将元素x添加至列表lst尾部 lst.extend(L)    | 将列表L中所有元素添加至列表lst尾部 lst.insert(index, x)  | 在列表lst制定位置index处添加元素x,该位置后面的所有元素后移一个位置 lst.remove(x)  | 在列表lst中删除首次出现的指定元素,该元素之后的所有元素前移一位 lst.pop([index])  | 删除并返回列表lst中下表为index(默认-1)的元素 lst.clear()  | 

python 中string类常用的方法

string                            aStr string.capwordsaStrspWord string.splitaStrspWord string.joinspWordrole string.maketrans, aStr aStr.translaterolevalue t string.Templatep t.substitutevaluep