s1 = 'Hello World'
s2 = "Python 字符串"
s3 = '''多行
字符串'''
s = "Python"
print(s[0]) # P (第一个字符)
print(s[-1]) # n (最后一个字符)
print(s[0:3]) # Pyt (切片,左闭右开)
print(s[::2]) # Pto (步长为2)
print(s[::-1]) # nohtyP (反转字符串)
s = "hello world"
print(s.find('o')) # 4 (首次出现位置,找不到返回-1)
print(s.find('o', 5)) # 7 (从索引5开始找)
print(s.index('o')) # 4 (与find类似,但找不到会报错)
print(s.rfind('o')) # 7 (从右边开始找)
s = "banana"
print(s.count('a')) # 3
print(s.count('na')) # 2
s = "example.txt"
print(s.startswith('ex')) # True
print(s.endswith('.txt')) # True
print(s.endswith(('.py', '.txt'))) # True (支持元组)
s = "Python3"
print(s.isalpha()) # False (含数字)
print("abc".isalpha()) # True (全是字母)
print("123".isdigit()) # True (全是数字)
print(" ".isspace()) # True (全是空格)
print("Title Case".istitle()) # True (首字母大写)
print("UPPER".isupper()) # True
print("lower".islower()) # True
s = "I like Java, Java is good"
print(s.replace('Java', 'Python'))
# I like Python, Python is good
print(s.replace('Java', 'Python', 1))
# I like Python, Java is good (只替换1次)
s = "Hello Python"
print(s.upper()) # HELLO PYTHON
print(s.lower()) # hello python
print(s.title()) # Hello Python (每个单词首字母大写)
print(s.swapcase()) # hELLO pYTHON (大小写互换)
s = " hello world "
print(s.strip()) # "hello world" (两边)
print(s.lstrip()) # "hello world " (左边)
print(s.rstrip()) # " hello world" (右边)
# 去除指定字符
print("###Python###".strip('#')) # Python
s = "apple,banana,orange"
print(s.split(',')) # ['apple', 'banana', 'orange']
s2 = "a b c d e"
print(s2.split()) # ['a', 'b', 'c', 'd', 'e'] (默认按空白分割)
print(s2.split(' ', 2)) # ['a', 'b', 'c d e'] (最多分割2次)
# 按行分割
s3 = "第一行\n第二行\n第三行"
print(s3.splitlines()) # ['第一行', '第二行', '第三行']
words = ['Hello', 'World', 'Python']
print(' '.join(words)) # Hello World Python
print('-'.join(words)) # Hello-World-Python
# 实际应用:拼接路径
paths = ['home', 'user', 'documents']
print('/'.join(paths)) # home/user/documents
s = "Python"
print(s.center(12, '-')) # ---Python--- (居中)
print(s.ljust(12, '*')) # Python****** (左对齐)
print(s.rjust(12, '*')) # ******Python (右对齐)
# 补零(常用于编号)
print("42".zfill(5)) # 00042
print("-42".zfill(5)) # -0042
name = "小明"
age = 20
print("我叫%s,今年%d岁" % (name, age))
print("我叫{},今年{}岁".format("小明", 20))
print("我叫{0},今年{1}岁".format("小明", 20))
print("我叫{name},今年{age}岁".format(name="小明", age=20))
# 格式化数字
print("{:.2f}".format(3.14159)) # 3.14
print("{:,}".format(1000000)) # 1,000,000
print("{:0>8}".format(42)) # 00000042
name = "小明"
age = 20
print(f"我叫{name},今年{age}岁")
# 表达式计算
a, b = 3, 5
print(f"{a} + {b} = {a + b}") # 3 + 5 = 8
# 格式化
pi = 3.1415926
print(f"圆周率:{pi:.2f}") # 圆周率:3.14
print(f"二进制:{10:b}") # 二进制:1010
print(f"百分比:{0.85:.1%}") # 百分比:85.0%
s = "你好,世界"
# 编码为字节
b = s.encode('utf-8')
print(b) # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
# 解码回字符串
print(b.decode('utf-8')) # 你好,世界
defclean_input(text):
return text.strip().lower().replace(' ', ' ')
print(clean_input(" Hello WORLD "))
# hello world
filename = "document.report.2024.pdf"
name, ext = filename.rsplit('.', 1)
print(f"文件名:{name}") # document.report.2024
print(f"扩展名:{ext}") # pdf
for i in range(1, 6):
print(f"编号:{str(i).zfill(3)}")
# 编号:001
# 编号:002
# 编号:003
# 编号:004
# 编号:005
text = "hello world hello python hello code"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
# {'hello': 3, 'world': 1, 'python': 1, 'code': 1}
len(s) | |
s[i] | |
s[a:b] | |
s.find()s.index() | |
s.count() | |
s.startswith()s.endswith() | |
s.replace() | |
s.upper()s.lower() | |
s.strip() | |
s.split() | |
s.join() | |
s.center()s.ljust() / s.rjust() | |
s.zfill() | |
s.format()f"..." | |
s.encode()s.decode() |
💡 小贴士:字符串在 Python 中是不可变的,所有修改方法都会返回新字符串,原字符串不会被改变。
整理不易,觉得有用的话欢迎点赞收藏转发!