python字符串数据操作
时间: 2024-01-03 08:04:15 浏览: 30
以下是Python中常见的字符串数据操作方法:
1. 检查字符串是否以给定字符串或字符结尾
```python
txt = "Canada is a great country"
x = txt.endswith("country")
print(x) # 输出:True
```
2. 在字符串中查找子字符串并返回其索引
```python
def find_str(s, char):
index = 0
if char in s:
c = char[0]
for ch in s:
if ch == c:
if s[index:index+len(char)] == char:
return index
index += 1
return -1
print(find_str("IndiaCanadaJapan", "Canada")) # 输出:5
print(find_str("IndiaCanadaJapan", "cana")) # 输出:-1
print(find_str("IndiaCanadaJapan", "Uae")) # 输出:-1
```
3. 将字符串转换为小写或大写
```python
txt = "Hello, World!"
print(txt.lower()) # 输出:hello, world!
print(txt.upper()) # 输出:HELLO, WORLD!
```
4. 从字符串中删除空格
```python
txt = " Hello, World! "
print(txt.strip()) # 输出:Hello, World!
```
5. 将字符串分割为子字符串列表
```python
txt = "apple, banana, cherry"
x = txt.split(", ")
print(x) # 输出:['apple', 'banana', 'cherry']
```