Blogger Information
Blog 10
fans 0
comment 5
visits 25339
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Python之字符串常用操作
晏南风i
Original
1486 people have browsed it
# 字符串的索引与切片
str = 'ABCDEFGHIJK'
print(str[0])       # A
print(str[3])       # D
print(str[5])       # F
print(str[7])       # H

"""
    何为切片?
    切片就是通过索引(索引:索引/索引:步长)截取字符串的一段
    切片的原则: 顾头不顾尾
"""
str = 'ABCDEFGHIJK'
print(str[0:3])     # A B C
print(str[2:5])     # C D E
print(str[0:])      # 包含A到字符串末尾
print(str[0:-1])    # 顾头不顾尾原则,反向-1位置的K会取不到 A
print(str[0:5:2])   # 从0开始到5位置结束,步长为2   A C E
print(str[5:0:-2])   # 反向加步长 F D B

# 字符串常用方法
name = input('请输入用户名:')

# 首字母大写
print(name.capitalize())

# 大小写翻转
print(name.swapcase())

# 每个单词的首字母大写
print(name.title())

# 居中并填充
print(name.center(20, '*'))

# 字符串中元素出现的个数
print(name.count("s"))
print(name.count('s', 3))

# 判断是否以...开头(Bool)
print(name.startswith('j'))
print(name.startswith('j', 1))

# 判断是否以...结尾(Bool)
print(name.endswith('e'))
print(name.endswith('e', 3))

# 寻找字符串中的元素是否存在 jesse
print(name.find('s'))
print(name.find('s', 3))

# 字符串转化为数组
print(name.split(','))
print(name.rsplit(',', 1))

# format的三种用法
print('{} {} {}'.format('jesse', 18, 'man'))
print('{1} {0} {1}'.format('jesse', 18, 'man'))
print('{name} {age} {sex}'.format(age=18, sex='man', name='jesse'))

# 去除两端字符
print(name.rstrip('*'))
print(name.lstrip('*'))
print(name.strip('*'))

# 字符串替换
print(name.replace('jesse', 'David', 1))


# is系列
print(name.isalnum())       # 字符串由数字或字母组成
print(name.isalpha())       # 字符串只由字母组成
print(name.isdigit())       # 字符串只由数字组成


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post