字符串常用的一些API(别人写的一些函数,我们直接使用)

一、字母大小写设置

text = "Hello World"
text2 = text.lower() # 小写
print(text2)
text3 = text.upper() # 大写
print(text3)
text4 = text.capitalize() # 首字母大写
print(text4)
text5 = text.title() # 每个单词的首字母大写
print(text5)

输出:

hello world
HELLO WORLD
Hello world
Hello World

二、去除分割连接替换操作

text ="  123456   "
text1 = text.strip() # 去除空格
print(text1)

text = "Hello World My name is LiHua"
text1 = text.split(" ") # 使用空格来分割字符串,返回值是一个列表,每个元素值是字符串中的一个单词。未来有一个工具叫jieba分词
print(text1)

text =["python","java","c++"]
text1 ="-".join(text) # 将列表中的元素以指定的符号连接起来,返回值是一个字符串。
print(text1)

text = "python"
text1 = text.replace("p","A") # 替换字符串中的某个字符
print(text1)

输出:

123456
['Hello', 'World', 'My', 'name', 'is', 'LiHua']
python-java-c++
Aython

三、查找计算操作

text = "python"
text1 = text.find("h",1) # 查找字符串中的某个字符,返回值是字符在字符串中的索引位置,没有则返回-1,1表示从第二个字符开始查找
print(text1)

text = "hello python"
text1 = text.count("l") # 计算字符串中某个字符出现的次数,返回值是整数
print(text1)

输出:

3
2

四、判断开头结尾操作

text = "python"
text1 = text.startswith("p") # 判断字符串是否以某个字符开头,返回值是布尔值
print(text1)
text2 = text.endswith("n") # 判断字符串是否以某个字符结尾,返回值是布尔值
print(text2)

输出:

True
True

五、判断字符串是否全为字母或数字操作

text = "1234"
text1 = text.isdigit() # 判断字符串是否全部是数字,返回值是布尔值
print(text1)
text2 = text.isalpha() # 判断字符串是否全部是字母,返回值是布尔值
print(text2)
text3 = text.isalnum() # 判断字符串是否全部是数字和字母,返回值是布尔值
print(text3)

输出:

True
False
True

六、格式化操作

较为原始的操作,但易出错:

text = "hello my name is {}, my age is {}"
name = "LiHua"
age = 18
text1 = text.format(name,age)
print(text1)

简便操作:

text2 = f"hello my name is {name}, my age is {age}"
print(text2)

输出:

hello my name is LiHua, my age is 18
hello my name is LiHua, my age is 18

你可能感兴趣的:(python,开发语言,学习方法)