str.py:
# -*- coding: utf-8 -*-
# 测试函数
def f():
# 字符串使用单引号定义
s1 = 'test'
print(s1)
# 字符串使用双引号定义
s2 = "test"
print(s2)
# 多行字符串使用三引号定义
s3 = '''
这是一个多行字符串
可以包含换行符
'''
print(s3)
# 字符串中包含转义字符
s4 = "hello
world"
print(s4)
# 原始字符串
s5 = r"hello world"
print(s5)
# 字符串的长度
print(len(s1))
# 字符串的索引
print(s1[0])
# 字符串的切片
print(s1[0:3])
# 字符串的遍历
for c in s1:
print(c)
# 字符串的拼接
s6 = s1 + s2
print(s6)
# 字符串的重复
s7 = s1 * 3
print(s7)
# 字符串的成员运算
print("t" in s1)
print("x" not in s1)
# 字符串的比较
print(s1 == s2)
print(s1 != s2)
# 字符串的比较
print(s1 < s2)
print(s1 > s2)
print(s1 <= s2)
print(s1 >= s2)
# 字符串的查找和替换
print(s1.find("t"))
print(s1.replace("t", "x"))
# 字符串的大小写转换
print(s1.upper())
print(s1.lower())
print(s1.title())
# 字符串的去空格
s8 = " hello world "
print(s8.strip())
# 字符串的左右去空格
s9 = " hello world "
print(s9.lstrip())
print(s9.rstrip())
# 字符串的格式化输出
print("hello %s" % "world")
print("hello %d" % 100)
print("hello %f" % 1.0)
# 字符串的格式化输出
print("hello %s, you are %d years old" % ("world", 100))
# 字符串的计数
print(s1.count("t"))
# 字符串的分割
print(s1.split("t"))
# 字符串的连接
print("".join(s1.split("t")))
s1.isalnum() # 字符串是否只包含字母和数字
s1.isalpha() # 字符串是否只包含字母
s1.isdigit() # 字符串是否只包含数字
if __name__ == '__main__':
f()
运行:
(.venv) PS > python str.py
test
test
这是一个多行字符串
可以包含换行符
hello
world
hello world
4
t
tes
t
e
s
t
testtest
testtesttest
True
True
True
False
False
False
True
True
0
xesx
TEST
test
Test
hello world
hello world
hello world
hello world
hello 100
hello 1.000000
hello world, you are 100 years old
2
['', 'es', '']
es
说明:
字符串操作在编写代码中使用频率是很高的,对它的常规操作需要很熟悉。
整体的过一遍python3中字符串的定义和常见操作就成为一种必要。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...


