字符串
是一个不可变的字节序列,通常用于表示文本数据。
定义
- 字符串的定义使用引号
''或者""包裹。 - 字符串是不可变数据类型。
python
str1 = "hello"基本操作
python
str1="hello world"
print (str1) # 输出完整字符串
print (str1[0]) # 输出字符串中的第一个字符
print (str1[2:5]) # 输出字符串中第三个至第六个之间的字符串
print (str1[2:]) # 输出从第三个字符开始的字符串
print (str1 * 2) # 输出字符串两次
print (str1 + "TEST") # 输出连接的字符串输出结果
hello world
h
llo
llo world
hello worldhello world
hello worldTEST
格式化
python
money = 50
ice_cream = 10
cole = 5
# 方式1
print("我有{}元,可以买{}个冰淇淋或者{}个可乐".format(money,int(money/ice_cream),int(money/cole)))
# 方式2
print("冰淇淋单价%s元,可乐单价%s元" % (ice_cream,cole))
# 方式3
print("我买了1冰淇淋和2可乐,还剩{money}元".format(money = money - ice_cream * 1 - cole * 2))
# 方式4 推荐方式
print(f"我买了1冰淇淋和2可乐,还剩{money-ice_cream*1-cole*2}元")f、r、u、b
f字符串格式化r原始字符串uUnicode 字符串b字节字符串
python
# 字符串格式化
name = "world"
str1 = f"hello {name}"
print(str1) # hello world
# 原始字符串
str1 = r"hello\nworld"
print(str1) # hello\nworld
# Unicode字符串
str3 = u"hello world"
print(str3) # u'hello world' 变成成字节
str4 = str3.decode("utf-8") # 解码成字符串
str4.encode("utf-8") # 编码成字节
# 字节字符串
str2 = b"hello world"
print(str2) # b'hello world'三引号
可以将复杂的字符串进行赋值,使用''' 或者 """ 包裹。
python
# 字符串原样输出
str2 = """
字符串 <script></script>
"""
print(str2)常用函数
python
str1="hello"| 函数名 | 作用 | 示例 | 结果 |
|---|---|---|---|
| capitalize() | 把字符串的第一个字符大写 | str1.capitalize() | Hello |
| lower() | 字符串转小写 | str1.lower() | hello |
| upper() | 字符串转大写 | str1.upper() | HELLO |
| count(value) | 统计字符串中某个字符出现的次数 | str1.count("l") | 2 |
| find(value) | 字符第一次出现的索引值,不存在返回-1 | str1.find("l") | 2 |
| replace(old,new) | 替换字符串中的某个字符 | str1.replace("e","g") | hgllo |
| split(value) | 分隔符截取字符串为列表 | str1.split("l") | ['he', '', 'o'] |
| strip() | 去掉字符串左右空格 | str1.strip() | hello |
