下标
str1="abcdefgh"##从0开始,0是a,1是b...
print(str1)
print(str1[2])##print(函数名[下标])
print(str1[1:4])##下标
print(str1[-4:-1])##倒数,从右往左数第四位至第二位
print(str1[-4:])##打印后四位
字符串输出
print("hello")
name = 1
print("hello %s" % name)
print(f'hello {name}')
输入
input
字符串查找
name = '''Books are friends, which can take us to the ocean of knowledge;
A book is a teacher. When I have a problem I don't understand, it can give me an answer;
Books are home. When we are lonely, they can bring us warmth and happiness'''##假如给我三天光明节选
print(name.find('are'))##检测某个子串所在位置下标,没有则返回-1
print(name.find('are',15,45))##选定范围15到45
'''rfind,用法相同,从右侧开始检测'''
print(name.index('are'))##检测某个子串所在位置下标,没有则报异常
print(name.index('are',1,9))##上同
##print(name.index('ares'))
'''rindex,用法相同,从右侧开始检测'''
print(name.count('are'))##检测字串在字符串中的出现次数
print(name.count('are',15,45))##上同
字符串修改
name = '''Books are friends, which can take us to the ocean of knowledge;
A book is a teacher. When I have a problem I don't understand, it can give me an answer;
Books are home. When we are lonely, they can bring us warmth and happiness'''##假如给我三天光明节选
##replace替换
new_name=name.replace('are','era',1)##字符串.replace('旧子串','新子串',替换次数) 替换次数可省略
print(f"{new_name}\n")
##split分割,返回列表,丢失分割子串
new_name1=name.split('are',2)####字符串.split('分割子串',分割次数) 分割次数可省略
print(f"{new_name1}\n")
##jion合并列表里的数据,变成一个字符串
my_list=['aaa','bbb','ccc']
new_my_list = 'xxx'.join(my_list)####字符串或子串.jion(列表)
print(new_my_list)
大小写转化
name = '''Books are friends, which can take us to the ocean of knowledge'''##假如给我三天光明节选
##catipalize,将字符串第一个字符转化为大写,其余小写
print(name.capitalize())
##title,将字符串中每个单词的首字母转化为大写,其余小写
print(name.title())
##lower,大转小
print(name.lower())
##upper,小转大
print(name.upper())
删除两侧空白字符
name = ''' Books are friends, which can take us to the ocean of knowledge '''##假如给我三天光明节选
##strip,删除两侧空白字符
print(name.strip())
'''lstrip,删除左侧空白字符;rstrip,删除右侧空白字符'''
字符串左中有对齐
name = 'Books'
'''ljust,左对齐
rjust,右对齐
center,居中
'''
print(name.ljust(10))##字符串.ljust(长度,填充字符)
print(name.ljust(10,'.'))
print(name.rjust(10))
print(name.center(10))
字符串判断
name = '''Books are friends, which can take us to the ocean of knowledge'''##假如给我三天光明节选
##startswith检查字符串是否以指定子串开头,是则返回true,否则返回false
print(name.startswith('Books'))
print(name.startswith('books'))##字符串.startswith('子串',开始位置下标,结束位置下标)
print(name.startswith('books',15,25))
##isalpha字符串至少有一个字符且所有字符都是字母则返回true,反之返回false
my_str='abcde'
my_str1='abcde12345'
print(my_str.isalpha())
print(my_str1.isalpha())
##isdigit字符串只包含数字则返回true,反之返回false
my_num='12345'
my_num1='12345a'
print(my_num.isdigit())
print(my_num1.isdigit())
'''isalnum字符串至少有一个字符且都是字母或数字返回true,反之false'''
print(my_num.isalnum())
my_num2='///123aa'
print(my_num2.isalnum())