字符串

test = 'alExAlexr'

# 首字母大写
test.capitalize()

# 将所有的字符变小写,包括一些未知的对应关系(别的语言)
test.casefold()

# 将字符串变为小写
test.lower()
#判断字符串是否全为小写
test.islower()

# 将字符串变为大写
test.upper()
#判断字符串是否全为大写
test.isupper()

#大写换小写,小写换大写
test.swapcase()

#删除左边,右边,两边的空格 	 

test.lstrip()
test.rstrip()
test.strip()
#还可以移除指定的字符,移除时会进行最大匹配(最长公共子序列)
test.lstrip('abc')

#分隔字符串
test = 'testasdsddfg'
print(test.partition('s'))       #从左往右找结果为('te', 's', 'tasdsddfg')
print(test.rpartition('s'))       #从右往左找结果为('testasd', 's', 'ddfg')
print(test.split('s', 2))       #从左向右找,找2次,s会被删除,结果为['te', 'ta', 'dsddfg']
print(test.rsplit('s', 2))       #从右向左找,找2次,s会被删除,结果为['testa', 'd', 'ddfg']

#根据换行符进行分隔字符串,True保留换行符,False不保留换行符
test = 'asdfsadf
sadfsdfsaf
asdfsd'
test.splitlines(True)

# 设置20宽度并将test居中,默认两边填充空格
test.center(20)
# 使用*号填充,此处填充的只能为单字符
test.center(20, '*')
#将字符串居左,或居右填充
test.ljust(20)
test.rjust(20)
#字符串居右,前面用0填充,不能指定填充字符
test.zfill(20)

# 计算r在test中出现的个数
test.count('r')
# 计算从下标从>=5开始,从<7结束的ex个数
test.count('ex', 5, 7)

# 判断test是否以a结尾
test.endswith('a')

# 判断test是否以a开头
test.startswith('a')

# 从开始往后找,找到第一个,获取下标,找不到返回-1
test.find('ex', 0, 5)

# 从开始往后找,找到第一个,获取下标,找不会报错
test.index('ex')

# 判断字符串中是否只是字符和数字
test = 'uasf890'
test.isalnum()

# 使用bbb替换ex,替换2次
test = 'alexalexalex'
test.replace('ex', 'bbb', 2)
# 格式化,将字符串中的占位符替换为指定的值
test = 'i am {name}, age {a}'
test.format(name
='alex', a=19)
test
= 'i am {0}, age {1}'
test.format(
'alex', 19)
test = "i am {name}, age:{age}"
test.format(**{"name": alex, "age": 19})


# 格式化,传入的值必须是一个字典
test = 'i am {name}, age {a}'
test.format_map({
"name": "alex", "a": 19})

# 把字符串中的 tab 符号(' ')转为空格
mystr = "1 2 "
print(mystr) # 4个空格
print(mystr.expandtabs()) # 8个空格 会把 转变成8个空格
print(mystr.expandtabs(tabsize=1)) # 1个空格 设置数量

test
= 'username email password laiying ying@163.com 123'
print(test.expandtabs(20))
# 结果为
#
  username     email        password
#
  laiying     ying @ 163.com  123

#判断字符串是否是字母,汉字
test = 'asdsdaf' test.isalpha()

#判断字符串是否是数字
test = '124'
test.isdecimal()

#判断字符串是否是数字,可以识别一些特殊的数字字符
test = ''
test.isdigit()


#判断字符串是否是数字,可以识别一些特殊的数字字符及中文大写数字
test = '二'

test.isnumeric()

#判断是否存在不可显示的字符,若有则为False
test = 'asidf dsff'
test.isprintable()

#判断字符串是否全都是空格
test.isspace()

#判断字符串是否每一个单词都是首字母大写的标题样式
test.istitle()

#将字符串转为每一个单词都是首字母大写的标题样式
test.title()

#将字符串的每个元素按照指定的分隔符进行拼接
test = '你是风儿我是沙'
v
= ' '.join(test)
print(v)
#结果为 你 是 风 儿 我 是 沙

#根据定义的对应关系将字符串的字符进行替换
test = 'sadfsolkdsiadluasdf'
m
= str.maketrans('aeiou', '12345') #创建对应关系
new_test = test.translate(m) #根据对应关系进行转换
print(new_test)

#判断字符串是否为标识符(字母数字及下划线组成,不得以数字开头)
test = 'def' test.isidentifier()

必须要掌握的是join split find strip upper lower replace

字符串一但创建就不可修改,一但修改或拼接都会生成一个新的字符串

字符串的切片

text = '你好,我是你的朋友'
print(text[0])
print(text[0:2])

num = 0
while num < len(text):
    print(text[num])
    num += 1

for item in text:
    print(item)


for item in range(0, len(text))
    print(item, text[item])

 

原文地址:https://www.cnblogs.com/dangrui0725/p/9398640.html