python——字符串

字符串
    1.创建:单引号, 双引号, 三引号 (转义字符: \', \\", \n, \t)
    2.特性:

        索引:s[第几个]


        切片:s[从哪里开始切(默认是0),切到哪里(默认字符串长度),步长多少(默认是1)],可以复制,很重要,


        成员操作符(重要):in, not in ,判断子串是否在其中


    3.字符串是可迭代对象,通过for实现循环;
    4.字符串的常用方法:

        1.判断字符串有什么组成    s.isdigit()(是否由纯数字组成)...


        2.判断是否以什么开头,什么结尾    
            s.startswith('http://')

            s.endswith('.png')


        3.去除字符串的左右的空格:只要应用在有用户输入数据的地方

            s.strip(),s.lstrip(),s.rstrip,s.replace(" ", "")


            重点!!!:s.replace方法也可以间接实现删除某个字符
        4.字符串对齐格式化:左对齐,右对齐,中间对齐
            s.center(40, "*")
            s.ljust(40, "*")

            s.rjust(40, "*")


        5.按照指定分隔符分离字符串:(默认分隔符为空格)
            ip = '172.25.254.250'

            ip.split('.')


        6.制定分隔符连接信息
            a = info.split()括号内要写出使用什么分隔符将字符串分隔开来

            '+'.join(a)    ##用加号将字符串连接起来


    5.字符串的内置方法(BIF-built-in function)

        cmp,len(重要,比较两个字符串的大小),max,min,枚举enumerate(s),zip


元组

# # 元组(带了紧箍咒的列表)
#
#
# ## 元组的创建

# - 通过赋值方式创建元组;
# - 通过工厂方法创建元组




# tuple
# 可以把元组看作一个容器,任何数据类型都可以放在这个容器里面;
t = (1, 1.0, 2j, True, (1,2,3))
print t





t = (1)
print type(t)

# 定义单个元组,一定要在这个元素后面加逗号
t1 = (1,)
print type(t1)





# 工厂方法
t = tuple()
print type(t)


# ## 元组的操作
#
# - 索引
# - 切片
# - 连接
# - 重复
# - 成员操作符



t = ("fentiao", 5, "male")

# 正向索引
print t[0]
# 反向索引
print t[-1]


# 元组嵌套时元素的访问
t1 = ("fentiao", 5, "male", ("play1", "play2", "play3") )
print t1[3][1]





# 切片
print t[:2]

# 逆转元组元素
print t[::-1]




# 连接
print t + t1




# 重复
t*3



# 成员操作符
allow_ips = ('172.25.254.1', '172.25.254.12', '172.25.254.13')

if "172.25.254.1" in allow_ips:
        print "有访问权限"
else:
        print "无访问权限"



# ## 元组的循环



# 字符串的循环:
# 可迭代对象
for i in "hello":
    print i



# 元组目前接触的第三个可迭代对象;
allow_ips = ('172.25.254.1', '172.25.254.12', '172.25.254.13')
for ip in allow_ips:
    print ip


# ### Demo: 端口扫描器雏形
#
#
#



ips = ('172.25.254.1', '172.25.254.12', '172.25.254.13')
ports = (80, 8080, 21, 22)

# 依次读取需要扫描的ip;
for ip in ips:
    # 依次读取要扫描的端口
    for port in ports:
        print "[+] Scaning %s:%d" %(ip, port)


# ## 元组可用的内置方法



print cmp(('a', 1,2,3,4), (1, 2,))

print max((12,34,12,56))


print min((12,34,12,56))




# 枚举
ips = ('172.25.254.1', '172.25.254.12', '172.25.254.13')
for i,j in enumerate(ips):
    print i,j



# zip:

username = ("user1", "user2", "user3")
password = ("123", "456", "789")

zip(username, password)


# ### 自动售货系统部分代码



# 枚举的使用

goods = (
    ("Apple", 2),
    ("Ipad",  4000),
    ("iWatch", 3500)
)


print "商品编号\t商品名称\t商品价格"
for index, value in enumerate(goods):
    print "%.3d\t%s\t%.2f" %(index, value[0], value[1])
    



# ## 元组的常用方法

t = (2, 1, 1, 2)
print t.count(1)
print t.index(1)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值