本关任务:编写字符串简单应用代码。 相关知识 为了完成本关任务,你需要掌握:字符串 获取数组的长度 Python中的字符串是用单引号(')、双引号(")或三引号(''')括起来,同时使用反斜杠(\)转义特殊字符的一段文字。 字符串是一个有序字符的集合,用于存储和表示基本的文本信息,但是只能存放一个值,一经定义,不可改变。 字符串可以通过切片操作得到子串 提供大量的字符串操作函数(P14)
时间: 2025-06-26 14:27:00 浏览: 10
### Python 字符串简单应用示例
以下是几个常见的字符串操作示例代码,涵盖了字符串拼接、查找子字符串、替换字符以及分割字符串等功能。
#### 1. 字符串拼接
可以通过加号 `+` 或者逗号 `,` 来实现字符串的连接。
```python
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2 + "!"
print(result) # 输出: Hello, World!
```
#### 2. 查找子字符串
使用 `.find()` 方法可以在字符串中查找指定子字符串的位置。如果找到则返回索引位置;如果没有找到,则返回 `-1`。
```python
text = "Python is a great programming language."
substring = "great"
position = text.find(substring)
if position != -1:
print(f"'{substring}' found at index {position}.") # 输出: 'great' found at index 11.
else:
print(f"'{substring}' not found.")
```
#### 3. 替换字符串中的特定字符
通过 `.replace(old_value, new_value)` 可以将字符串中的某些部分替换成新的内容[^3]。
```python
original_string = "Python is fun to learn."
modified_string = original_string.replace("fun", "awesome")
print(modified_string) # 输出: Python is awesome to learn.
```
#### 4. 分割字符串
`.split(separator)` 是一种用于按分隔符拆分字符串的方法,并将其转换成列表形式。
```python
sentence = "This,is,a,test,sentence."
words_list = sentence.split(",")
print(words_list) # 输出: ['This', 'is', 'a', 'test', 'sentence.']
```
#### 5. 转换大小写
利用 `.upper()` 和 `.lower()` 函数分别把整个字符串转为大写或小写状态。
```python
sample_text = "Mixed CASE String"
uppercase_version = sample_text.upper()
lowercase_version = sample_text.lower()
print(uppercase_version) # 输出: MIXED CASE STRING
print(lowercase_version) # 输出: mixed case string
```
以上就是一些基础却实用的 Python 字符串操作例子[^1][^2]。
阅读全文
相关推荐


















