# 单引号创建
str1 = 'hello world'
# 双引号创建(与单引号无本质区别)
str2 = "hello world"
# 三引号创建多行字符串
str3 = '''第一行
第二行
第三行'''
# 转义字符处理引号嵌套
str4 = '拾光 "Hello"'
str5 = "拾光 'Hello'"s = "hello"
# s[0] = 'H' # 会报错:'str' object does not support item assignmentfor char in "hello":
print(char)s = "hello"
print(len(s)) # 输出:5从 0 开始计数:
s = "python"
print(s[0]) # 输出:p
print(s[2]) # 输出:t支持负数索引(从末尾开始计数):
s = "python"
print(s[-1]) # 输出:n(最后一个字符)
print(s[-3]) # 输出:h切片用于获取字符串的子串,语法:s[start:end:step]
s = "abcdefgh"
# 获取从索引1到4(不包含4)的子串
print(s[1:4]) # 输出:bcd
# 从开始到索引3
print(s[:4]) # 输出:abcd
# 从索引5到结束
print(s[5:]) # 输出:fgh
# 步长为2(每隔一个字符取一个)
print(s[::2]) # 输出:aceg
# 反转字符串
print(s[::-1]) # 输出:hgfedcba 高频面试题s = "Hello World"
print(s.lower()) # 全部小写:hello world
print(s.upper()) # 全部大写:HELLO WORLD
print(s.title()) # 首字母大写:Hello World
print(s.capitalize()) # 第一个单词首字母大写:Hello world
print(s.swapcase()) # 大小写互换:hELLO wORLDs = "hello world, hello python"
# 查找子串位置
print(s.find("hello")) # 输出:0(首次出现的位置)
print(s.rfind("hello")) # 输出:13(最后出现的位置)
print(s.index("world")) # 输出:6(与find类似,但找不到会报错)
# 替换子串
print(s.replace("hello", "hi")) # 输出:hi world, hi python
print(s.replace("hello", "hi", 1)) # 只替换第一次出现s = " hello world \n"
print(s.strip()) # 去除两端空白:hello world
print(s.lstrip()) # 去除左端空白:hello world
print(s.rstrip()) # 去除右端空白: hello worlds = "apple,banana,orange"
# 分割字符串
print(s.split(",")) # 输出:['apple', 'banana', 'orange']
print(s.split(",", 1)) # 只分割一次:['apple', 'banana,orange']
# 连接字符串
fruits = ['apple', 'banana', 'orange']
print(",".join(fruits)) # 输出:apple,banana,oranges1 = "hello"
s2 = "12345"
s3 = "Hello123"
print(s1.isalpha()) # 全是字母:True
print(s2.isdigit()) # 全是数字:True
print(s3.isalnum()) # 字母和数字:True
print(s1.islower()) # 全小写:True
print(s3.istitle()) # 首字母大写:False
print(s1.startswith("he")) # 以指定字符串开头:True
print(s1.endswith("lo")) # 以指定字符串结尾:True# 获取字符的 Unicode 编码
print(ord('A')) # 65
print(ord('中')) # 20013
# 根据 Unicode 编码获取字符
print(chr(65)) # A
print(chr(20013)) # 中#Python #Python字符串