字符串切片
使用切片语法 `string[start:stop]` 来获取子字符串,其中 `start` 是起始索引(包含),`stop` 是终止索引(不包含)。
s = 'hello world'
print(s[0:5]) 输出 'hello'
print(s[6:]) 输出 'world'
`split` 方法
使用 `split` 方法根据指定的分隔符将字符串分割成子字符串列表。
s = 'hello,world'
print(s.split(',')) 输出 ['hello', 'world']
`find` 或 `index` 方法
使用 `find` 或 `index` 方法查找子字符串在字符串中的位置,返回子字符串首次出现的索引,如果找不到则返回 `-1`。
s = 'hello world'
print(s.find('world')) 输出 6
`in` 关键字
使用 `in` 关键字检查一个字符串是否包含另一个子字符串。
s = 'hello world'
print('world' in s) 输出 True
负索引
Python中的索引可以是负数,表示从字符串的末尾开始计数。
s = 'hello world'
print(s[-1]) 输出 'd'
获取特定位置的字符
使用切片语法 `string[index]` 来获取特定位置的字符。
s = 'hello world'
print(s) 输出 'o'
以上方法可以帮助你在Python中获取子字符串。请根据你的具体需求选择合适的方法