建立字符串
s1 = "Hello"
s2 = 'Hello'
s3 = """多行字符串"""
取得字元(Indexing)
索引从 0 开始:
s = "Python"
print(s[0]) # P
print(s[-1]) # n(倒数第一个)
字符串切片(Slicing)
s = "Python"
print(s[1:4]) # yth
print(s[:3]) # Pyt
print(s[3:]) # hon
print(s[::-1]) # n o h t y P (倒序)
字符串长度
len("Hello") # 5
字串拼接(Concatenation)
"Hello " + "World"
重复字符串
"Ha" * 3 # HaHaHa
检查内容(in / not in)
"py" in "python" # True
"java" not in "python" # True
转大小写
s.lower() # 全小写
s.upper() # 全大写
s.title() # 每个字首大写
s.capitalize() # 第一个字母大写
去除空白
s.strip() # 去掉左右空白
s.lstrip() # 左边空白
s.rstrip() # 右边空白
替换(Replace)
s.replace("old", "new")
分割(Split)
"apple,banana,mango".split(",")
# ['apple', 'banana', 'mango']
合并字符串(Join)
",".join(["a", "b", "c"])
# a,b,c
查找位置
s.find("lo") # 找到回传 index,找不到回传 -1
s.index("lo") # 找不到会报错
统计次数
"hello".count("l") # 2
检查开头结尾
s.startswith("He")
s.endswith(".txt")
字符串判断
这些都会回传 True / False:
s.isdigit() # 是否只有数字
s.isalpha() # 是否都是字母
s.isalnum() # 字母或数字
s.islower() # 是否全小写
s.isupper() # 是否全大写
s.isspace() # 是否全部为空白