字符串

字符串是一个有序的字符的集合,勇于存储和表示基本的文本信息,一堆单、双、三引号中间包含的内容称为字符串。

创建:

  s = "Hello,beauty! How are you?"

特性:

  有序、不可变

##字符串
s = "Hello,Beauty! How Are You?"
n = s.swapcase()  #大写变小写,小写变大写
print(s.capitalize()) #首字母大写
# print(n)
print(s.casefold()) #把所有的变成小写
print(s.center(80,'*')) #以S为中心,两天填充指定的字符,80为总长度。两边对齐
print(s.count('o')) #统计元素‘o’ 有几个
print(s.count('o',0,5)) #以索引为基础统计从0到5有几个‘o’
print(s.endswith('?')) #以什么结尾,返回True  or False
b = 'a	b'
print(b.expandtabs(20))  #扩展tab键
print(s.find('O')) #从左到右查找,找到就返回,没有返回-1
print(s.find('o',0,5)) #索引为基础从左到右查找,找到就返回,没有返回-1
#format 格式化
s1 = 'my name is {0},i am {1} years old!'
print(s1.format('chris',22))
s2 = 'my name is {name},i am {age} years old!'
print(s2.format(name='chris',age=22))
print(s.index('o')) #返回索引值,也可以start和end
print(s.lower())   #全部变小写
print(s.upper())   #全部变大写
print(s.strip())   #去掉两边的空格和换行
#用处
while True:
    name=input('user: ').strip()
    password=input('password: ').strip()
    if name == 'egon' and password == '123':
        print('login successfull')

print(s.split())   #把字符串变成列表,默认一空格分
print(s.splitlines()) #按行来分
print(s.replace('o','O'))   #替换,把old在前,new在后,默认替换所有
print(s.replace('o','O',1))   #替换,换几次O,把old在前,new在后
print('b'.isalnum()) #判断是不是阿拉伯数字或字符
print('22'.isalpha()) #判断是不是阿拉伯字符
print('22'.isdecimal()) #判断是不是整数
print('22'.isdigit())  #判断是不是整数
print('22'.isnumeric())  #判断是不是整数
print('_name_3'.isidentifier()) #判断是不是合法的变量名
print('_Name_4'.islower())   #判断是不是小写
print('33'.isprintable())   #判断是不是能打印的,二进制文件不能打印
print(' '.isspace())  #判断是不是空格
print(s.istitle())   #判断单词首字母是不是大写
print(s.isupper()) #判断是不是都是大写
names = ['alex','luffy','Chris']
print(','.join(names))  #把列表转换成字符串,‘’里面是区分元素的符号,如空格、-、_、#
print(s.ljust(40,'-')) #从左边开始把字符串填充到指定长度,类似center
##语法: str.maketrans(intab, outtab]);
'''
maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式, 
第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。 
注:两个字符串的长度必须相同,为一一对应的关系。
'''
str_in = 'abcdef'
str_out = '!@#$%^'
table = str.maketrans(str_in,str_out)
s = 'are you abc'
print(s.translate(table))
#长度len
# print(len('hell 123'))

重点:

  isdigit()

  replace()

  find()

  count()

  strip()

  center()

  splist()

  format()

  ','.join

ਁᒧԀฎӞӻํଧጱਁᒧጱᵞ҅ݳአԭਂؙ޾ᤒᐏच๜ጱ
෈๜௳҅מӞ੒̵౲݌̵ܔӣ୚ݩӾᳵ۱ތጱٖ਻ᑍԏԅ
ਁᒧԀ

原文地址:https://www.cnblogs.com/chris3201/p/8919725.html