python之基本数据类型(数字&字符串)

 

 

数字(Number)类型

 

python中数字有四种类型:整数、布尔型、浮点数和复数。

 

  • int (整数), 如 1, 只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。
  • bool (布尔), 如 True。
  • float (浮点数), 如 1.23、3E-2
  • complex (复数), 如 1 + 2j、 1.1 + 2.2j

数字 - int ,所有的功能,都放在int里:

 

1.将字符串转换为数字

a = "123"

print(type(a),a)     ==》<class 'str'> 123

 b = int(a)

print(type(b),b)     ==》<class 'int'> 123

 #按进制进行转换(base) 

num = "0011"

v = int(num, base=16)                 #按16进制转换

print(v)                   ==》17

2.- bit_lenght   # 当前数字的二进制,至少用n位表示

r = age.bit_length()

 

 

字符串(String)

 

  • python中单引号和双引号使用完全相同。
  • 使用三引号('''或""")可以指定一个多行字符串。
  • 转义符 '\'
  • 反斜杠可以用来转义,使用r可以让反斜杠不发生转义。。 如 r"this is a line with \n" 则\n会显示,并不是换行。
  • 按字面意义级联字符串,如"this " "is " "string"会被自动转换为this is string。
  • 字符串可以用 + 运算符连接在一起,用 * 运算符重复。
  • Python 中的字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
  • Python中的字符串不能改变。
  • Python 没有单独的字符类型,一个字符就是长度为 1 的字符串。
  • 字符串的截取的语法格式如下:变量[头下标:尾下标]
 1 str='Runoob'
 2  
 3 print(str)                 # 输出字符串
 4 print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
 5 print(str[0])              # 输出字符串第一个字符
 6 print(str[2:5])            # 输出从第三个开始到第五个的字符
 7 print(str[2:])             # 输出从第三个开始的后的所有字符
 8 print(str * 2)             # 输出字符串两次
 9 print(str + '你好')        # 连接字符串
10  
11 print('------------------------------')
12  
13 print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
14 print(r'hello\nrunoob')     # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
15 
16 输出:
17 Runoob
18 Runoo
19 R
20 noo
21 noob
22 RunoobRunoob
23 Runoob你好
24 ------------------------------
25 hello
26 runoob
27 hello\nrunoob
实例

 

 

 1 首字母大写capitalize()

 test = "aLex"

v = test.capitalize()

 print(v)               ==》Alex

2 所有变小写casefold()lower(),casefold更强大,很多未知的对应变小写

v1 = test.casefold()

print(v1)

v2 = test.lower()                        (ps:islower判断是否全是小写)

print(v2)

3 设置宽度,并将内容居中center()

# 20 代指总长度

# *  空白未知填充,一个字符,可有可无

test = "alex"

v = test.center(20,"")

print(v)                            ==》中中中中中中中中alex中中中中中中中中

 #ljust()放左边

 test = "alex"

 v = test.ljust(20,"*")

print(v)                             ==》alex****************

 #rjust()放右边

test = "alex"

v = test.rjust(20,"*")

print(v)                             ==》****************alex

#zfill()返回指定长度的字符串,原字符串右对齐,前面填充0。 

test = "alex"

v = test.zfill(20)

print(v)                             ==》0000000000000000alex

 

4 去字符串中寻找,寻找子序列的出现次数count()

test = "aLexalexr"

v = test.count('ex')

print(v)                       ==>2

 

test = "aLexalexr"

v = test.count('ex',5,6)             #在(5,6)的位置寻找

print(v)                     ==>0

 

5.判断是否以什么什么结尾endswith(),以什么什么开始startswith()

test = "alex"

v1 = test.endswith('ex')      

print(v1)                            ==》True

v 2= test.startswith('ex')

print(v2)                            ==>Flase

 

6 expandtabs()把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8

test = "username\temail\tpassword\nlaiying\tying@q.com\t123\nlaiying\tying@q.com\t123\nlaiying\tying@q.com\t123"

v = test.expandtabs(20)              #断句20,\t补齐20,\n换行     

print(v)

 

输出结果:
username            email               password
laiying             ying@q.com          123
laiying             ying@q.com          123
laiying             ying@q.com          123

  

7.find() 从开始往后找,找到第一个之后,获取其位置,找不到返回-1

# > >=

test = "alexalex"

v = test.find('ex')

print(v)                          ==》2

 

8 index()等同于find()但是index找不到会报错,可忽略,推荐使用find()

test = "alexalex"

v = test.index('8')

print(v)                                   ==》ValueError: substring not found

9.format() 格式化,将一个字符串中的占位符替换为指定的值

test = 'i am {name}, age {a}'

v = test.format(name='alex',a=19)

print(v)                               ==>i am alex, age 19

#也可用0,1...表示: 

test = 'i am {0}, age {1}'

v = test.format('alex',19)

print(v)                                 ==>i am alex, age 19

10 .format_map()格式化,传入字典的值 {"name": 'alex', "a": 19}

test = 'i am {name}, age {a}'

v1 = test.format(name='df',a=10)

v2 = test.format_map({"name": 'df', "a": 10})

 均能输出:i am alex, age 19

11 isalnum()判断字符串中是否只包含字母和数字

test = "123"

v = test.isalnum()

print(v)                       ==》True

12.isalpha()判断 是否只包含字母,汉字

test = "as2df"

v = test.isalpha()

print(v)          ==》Flase

 

13 isdecimal() isdigit() isnumeric()判断当前输入是否是数字

test = "" # 1,②

v1 = test.isdecimal()                 #用的多

v2 = test.isdigit()                       #可判断特殊字符比如②

v3 = test.isnumeric()                #能判断汉字“二”

print(v1,v2,v3)                    ==》False False True

14.isprintable()判断 是否存在不可显示的字符

# \t   制表符

# \n   换行

test = "oiuas\tdfkj"

v = test.isprintable()

print(v)                  ==》Flase

 

15 isspace()判断是否全部是空格

test = ""

v = test.isspace()

print(v)                 ==》Flase

 

16istitle() 判断是否是标题

test = "Return True if all cased characters in S "

v1 = test.istitle()

print(v1)                        ==》Flase

v2 = test.title()               #title()转换为标题

print(v2)                       ==》Return True If All Cased Characters In S                       

v3 = v2.istitle()

print(v3)                        ==》True

 

17.join()将字符串中的每一个元素按照指定分隔符进行拼接

test = "你是风儿我是沙"

v = "_".join(test)

print(v)                                ==》你_是_风_儿_我_是_沙

 

18 判断是否全部是大小写 和 转换为大小写

test = "Alex"

v1 = test.islower()        #判断是否为小写

v2 = test.lower()          #转换为小写

print(v1, v2)               ==>Flase  alex

 

v1 = test.isupper()        #判断是否为大写

v2 = test.upper()          #转换为大写

print(v1,v2)                ==》False ALEX

19.lstrip()  rstrip() 默认去除左右空白, 去除\t \n,也可去除指定字符,优先最多匹配

test = "xa"

v = test.lstrip('xa')

v = test.rstrip('9lexxexa')

v = test.strip('xa')

print(v)

20 translate()对应关系替换

test =  "aeiou"

 test1 = "12345"

v = "asidufkasd;fiuadkf;adfkjalsdjf"

m = str.maketrans("aeiou", "12345")

new_v = v.translate(m)

print(new_v)    ==》1s3d5fk1sd;f351dkf;1dfkj1lsdjf

 

21 partition()分割为三部分

test = "testasdsddfg"

v = test.partition('s')

print(v)                          ==》('te', 's', 'tasdsddfg')

v = test.rpartition('s')

print(v)                            ==》('testasd', 's', 'ddfg')

 

22 split()分割为指定个数,分割完不包含分割元素

v = test.split('s',2)

print(v)                              ==》['te', 'ta', 'dsddfg']

vv=test.rsplit(‘s’,3)                        

print(vv)                        ==》['te', 'ta', 'd', 'ddfg']

 

 

23splitlines()只能根据换行符分割truefalse:是否保留换行

test = "asdfadfasdf\nasdfasdf\nadfasdf"

v = test.splitlines(False)

print(v)           ==》['asdfadfasdf', 'asdfasdf', 'adfasdf']

 

 

 

24 swapcase()大小写转换(大-小,小-大)

test = "aLex"

v = test.swapcase()

print(v)                 ==》AlEX

 

25 isidentifier()判断是否为Python中的标识符字母,数字,下划线 : 标识符 def  class

a = "def"

v = a.isidentifier()

print(v)             ==》True

26 replace()将指定字符串替换为指定字符串

test = "alexalexalex"

v = test.replace("ex",'bbb')

print(v)                                  ==》albbbalbbbalbbb

v = test.replace("ex",'bbb',2)           #2表示替换前两个

print(v)                                    ==》albbbalbbbalex

###################### 7个基本魔法 ######################

# join       # '_'.join("asdfasdf")

# split

# find

# strip

# upper

# lower

# replace

###################### 4个灰魔法 ###################### 

一、for循环

# for 变量名 in 字符串:

#     变量名

# break

# continue

 

test = "hello"
index = 0
while index < len(test):
    v = test[index]
    print(v)
    index += 1
print('=======')
输出结果:
h
e
l
l
o
=======



for he in test:
    print(he)       ==》h
                                e
                                l
                                l
                                o



test = "郑建文妹子有种冲我来"

for item in test:

    print(item)

    break        ==》郑

 二、索引,下标,获取字符串中的某一个字符

test="alex"

v = test[3]

print(v)    ==>x

 三、切片

test="alex"

v = test[0:-1]               # 0=<  <-1     

print(v)           ==>ale

四、获取长度

Python3len获取当前字符串中由几个字符组成

test="alex"

v = len(test)

print(v)           ==>4

 五、range获取连续或不连续的数字,

# Python2中直接创建在内容中

# python3中只有for循环时,才一个一个创建

r1 = range(10)           # 0=<    <10

r2 = range(1,10)        #1=<     <10

r3 = range(1,10,2)

# 帮助创建连续的数字,通过设置步长来指定不连续

v = range(0, 20, 5)             

for item in v:

     print(item)        ==> 0 5 10 15

 

##### 练习题:根据用户输入的值,输出每一个字符以及当前字符所在的索引位置 #####

test = input(">>>")

for item in test:

     print(item)

 

将文字对应的索引打印出来:

test = input(">>>")

print(test)            # test = qwe   test[0]   test[1]

l = len(test)           # l = 3

print(l)

 

# r = range(0,l) # 0,3

# for item in r:

#     print(item, test[item])       # 0 q,1 w,2 e

 

# test = input(">>>")

# for item in range(0, len(test)):

#     print(item, test[item])

###################### 1个深灰魔法 ######################

# 字符串一旦创建,不可修改

# 一旦修改或者拼接,都会造成重新生成字符串

 

name = "zhengjianwen"

age = "18"

info = name + age

print(info)           ==>zhengjianwen18

posted @ 2018-07-08 14:01  一只小妖  阅读(985)  评论(0)    收藏  举报