■ 将字符串"My name is Liming"中所有英文字符改为小写字母 ■ 取出字符串"My name is Liming"第8-13个字符 ■ 将字符串"My name is Liming"转换为"My name is Lilei"
时间: 2024-10-08 13:05:45 浏览: 23
C语言中计算字符串长度与分割字符串的方法
在Python中,你可以使用内置的字符串方法来实现这三个需求:
1. **将所有英文字符改为小写字母**:
```python
s = "My name is Liming"
lower_case_s = s.lower()
print(lower_case_s) # 输出: "my name is liming"
```
2. **取出第8-13个字符** (注意Python索引从0开始,所以实际上是9-14):
```python
sliced_s = s[8:14]
print(sliced_s) # 输出: "name is "
```
3. **替换指定字符**:
要将"M"替换为"L",你需要先创建一个新的字符串,然后逐个字符替换:
```python
new_name = s.replace("M", "L")
print(new_name) # 输出: "My name is Liling"
```
若要完全替换名字部分,需要知道目标名称,这里直接替换第一个"M"到"I"前的所有"M":
```python
target_start_index = s.index("M") + 1
replacement = s[target_start_index:s.find(" ", target_start_index)]
final_s = s[:target_start_index] + "L" + replacement[1:]
print(final_s) # 输出: "My name is Lilei"
```
阅读全文