3、python字符的使用

字符串

定义: 在引号内,是一系列字符

"hello world"
"hello python"

1、使用变量保存字符串

a = "hello python "

2、一些简单的使用方法

首字母大写

name = "lada"
print(name.title())   # Lada

全部大写

a = "apple"
print(a.upper())   # APPLE

全部小写

a = "PYTHON"
print(a.lower())  # python

合并字符串

a = "hello"
b = "python"
print(a+" "+b)   # hello python

删除开头空白

a = "   python"
print(a.lstrip())

删除结尾空白

a = "python     "
print(a.rstrip())

删除两侧空白

a = "   python    "
print(a.strip())

将字符串转换成列表

a = "python"
print(list(a))  # ['p','y','t','h','o','n']

文本切割 split

a = "I love you"
print(a.split(" "))  # ['I','love','you']

判断字符串是以什么开头

a = "python"
print(a.startswith("p"))  # True
print(a.startswith("h"))  # False

判断字符串是以什么结尾

a = "python"
print(a.endswith("n"))  # True
print(a.endswith("x"))  # False

返回查找字符的索引(位置) index 找不到,原地报错

a = "python"
print(a.index("h"))   # 3

字符串的替换 replace

a = "i love you!"
print(a.replace("love" , "x")) 

join

a = "python"
print("*".join(a))

字符计数

a = "python"
print(a.count("p"))  #  1

查找 find 找不到返回 -1

a = "python"
print(a.find("n")) # 5
print(a.find("x")) # -1
原文地址:https://www.cnblogs.com/hefany/p/14220590.html