?对引号字符串或三引号字符串,如果需要用到引号则需要在前面增加"/"转义字符,三引号形式的字符串?持换?。
a = ‘i‘
b = "also"
c = ‘‘‘like‘‘‘
d = """python"""
e = ‘i\‘am vincent‘
print(a)
print(b)
print(c)
print(d)
print(e)
控制台显示结果为<class ‘str‘>,即数据类型为str(字符串)。
在Python中,使? input() 接收?户输?。
name = input(‘请输?你的名字:‘)
print(‘你的名字是%s‘ % name)
print(type(name))
password = input(‘请输?你的密码:‘)
print(f‘你的密码是{password}‘)
print(type(password))
切?是指对操作的对象截取其中?部分的操作。字符串、列表、元组都?持切?操作。
语法:序列[开始位置下标:结束位置下标:步?]
- 不包含结束位置下标对应的数据, 正负整数均可
- 步?是选取间隔,正负整数均可,默认步?为1。
name = "abcdef"
print(name[2:4:1]) # cd
print(name[2:4]) # cd
print(name[:4]) # abcd
print(name[1:]) # bcdef
print(name[:]) # abcdef
print(name[::2]) # ace
print(name[:-1]) # abcde, 负1表示倒数第?个数据
print(name[-3:-1]) # de
print(name[::-1]) # fedcba
查找?法即是查找?串在字符串中的位置或出现的次数
语法:字符串序列.find(?串, 开始位置下标, 结束位置下标)
开始和结束位置下标可以省略,表示在整个字符串序列中查找。
mystr = ‘i like python and java and c++ and php‘
print(mystr.find(‘and‘)) # 14
print(mystr.find(‘and‘, 15, 30)) # 23
print(mystr.find(‘amd‘)) # -1
语法:字符串序列.index(?串, 开始位置下标, 结束位置下标)
开始和结束位置下标可以省略,表示在整个字符串序列中查找
mystr = ‘i like python and java and c++ and php‘
print(mystr.index(‘and‘)) # 14
print(mystr.index(‘and‘, 15, 30)) # 23
print(mystr.index(‘amd‘)) # -1
语法:字符串序列.count(?串, 开始位置下标, 结束位置下标)
开始和结束位置下标可以省略,表示在整个字符串序列中查找。
mystr = ‘i like python and java and c++ and php‘
print(mystr.count(‘and‘)) # 3
print(mystr.count(‘and‘, 15, 30)) # 1
print(mystr.count(‘amd‘)) # 0
修改字符串指的就是通过函数的形式修改字符串中的数据
语法:字符串序列.replace(旧?串, 新?串, 替换次数)
mystr = ‘i like python and java and c++ and php‘
print(mystr.replace(‘and‘, ‘和‘))
print(mystr.replace(‘and‘, ‘和‘, 5))
print(mystr)
输出结果为:
i like python 和 java 和 c++ 和 php
i like python 和 java 和 c++ 和 php
i like python and java and c++ and php
数据按照是否能直接修改分为可变类型和不可变类型两种。字符串类型的数据修改的时候 不能改变原有字符串,属于不能直接修改数据的类型即是不可变类型
语法:字符串序列.split(分割字符, num)
mystr = ‘i like python and java and c++ and php‘
print(mystr.split(‘and‘))
print(mystr.split(‘and‘, 2))
print(mystr.split(‘ ‘))
print(mystr)
输出结果为:
[‘i like python ‘, ‘ java ‘, ‘ c++ ‘, ‘ php‘]
[‘i like python ‘, ‘ java ‘, ‘ c++ and php‘]
[‘i‘, ‘like‘, ‘python‘, ‘and‘, ‘java‘, ‘and‘, ‘c++‘, ‘and‘, ‘php‘]
i like python and java and c++ and php
语法:字符或?串.join(多字符串组成的序列)
mylist = [‘python‘, ‘java‘, ‘c++‘, ‘php‘]
print(‘ ‘.join(mylist))
print(‘...‘.join(mylist))
print(mylist)
输出结果为:
python java c++ php
python...java...c++...php
[‘python‘, ‘java‘, ‘c++‘, ‘php‘]
语法:字符串序列.ljust(?度, 填充字符)
判断即是判断真假,返回的结果是布尔型数据类型:True 或 False
语法:字符串序列.startswith(?串, 开始位置下标, 结束位置下标)
mystr = ‘i like python and java and c++ and php‘
print(mystr.startswith(‘i‘)) # True
print(mystr.startswith(‘i like‘)) # True
print(mystr.startswith(‘he‘)) # False
原文:https://www.cnblogs.com/guixinchn/p/13659449.html