字符串常见操作
转换字符串
str()
字符串组合
+
下标和切片
左闭右开
正序 [0:]
逆序 [::-1]
长度
len()
个数
count()
查找
find()
rfind()
index()
rindex()
替换
replace()
字符串切割
split() 返回列表
splitline() 返回列表
partition() 返回元组
rpartition()
注意区别:一个返回列表,一个返回元组
判断开头/结尾
startswith()
endswith()
大小写转换
title() 所有单词首字母大写
capitalize() 字符串的首字母大写
upper() / lower()
对齐
ljust()
rjust()
center()
删除空格
lstrip() 删除左边空格
rstrip() 删除右边空格
strip() 删除全部空格
判断字母/数字
isalpha()
isdigit()
isalnum()
组合列表
join() 将列表组合为字符串
问题
test = “aa bb \t cc \t dd”
如何删除test中的空格和\t ?
split()
如何再组合成新的字符串 ?
join()
name = "zhangsan"
#获取长度
print(len(name))
age = 18
#转换为转字符串
print(type(str(age)))
#字符串组合
a = "zhang"
b = "san"
c = a + b
print(c)
#打印 '===zhangsan==='
print("===%s==="%(a+b))
#下标和切片(左闭右开)
print(name[0:]) #正序
print(name[::-1]) #逆序
#常见操作
#查找字符串位置 find() index()
my_str = " flying in the world together world "
print(my_str.find("world")) #查找字符串位置(从左到右)找不到返回-1
print(my_str.find("is"))
print(my_str.rfind("world")) #从右开始查找
print(my_str.index("world")) #找不到返回异常
print(my_str.rindex("world"))
#个数 count()
print(my_str.count("world")) #返回单词个数
#替换 replace()
print(my_str.replace("world","WORLD")) #原字符串没有变化
#切割 split() 返回的是列表
print(my_str.split(" "))
#按照换行符切割 splitlines() 返回列表
test_str = "hello\nworld\n"
print(test_str.splitlines())
#字符串切割 partition()/rpartition() 返回元组
print(my_str.partition("world"))
print(my_str.rpartition("world"))
#首字母大写 title()
print(my_str.title())
#字符串首字母大写 capitalize()
print(my_str.capitalize())
#字符串中大写字符转变为小写字符 upper()/lower()
print(my_str.lower())
print(my_str.upper())
#判断以xxxx开头或者结尾 startswith() endswith() 返回值为Ture
filename = 'helloworld.txt'
print(filename.startswith("hello"))
print(filename.endswith(".txt"))
#对齐(左对齐/右对齐/居中)ljust()/rjust()/center()
print(my_str.ljust(50))
print(my_str.rjust(50))
print(my_str.center(50))
#删除空格 lstrip()/rstrip()/strip()
print(my_str.lstrip())
print(my_str.rstrip())
print(my_str.strip())
#判断是否是字母/数字/数字和字母组合 isalpha()/isdigit()/isalnum()
print(my_str.isalpha())
print(my_str.isdigit())
print(my_str.isalnum())
#组合列表形成一个字符串 join()
a = ["aaa","bbb","ccc"]
b = "="
print(b.join(a))
c = " "
print(c.join(a))
'''
test = "aa bb \t cc \t dd"
如何删除test中的空格和\t?
如何再组合成新的字符串?
'''
test_str = "aa bb \t cc \t dd"
print(test_str)
print(test_str.split())
result = test_str.split()
c = ""
print(c.join(result))