python中的字符串方法
在 Python 中,字符串是不可变的序列,有许多内置的方法用于对字符串进行各种操作。以下是一些常见的字符串方法:
1. 字符串长度:
```python
my_string = "Hello, World!"
length = len(my_string)
print(length) # 输出:13
```
2. 字符串切片:
```python
my_string = "Hello, World!"
substring = my_string[7:12]
print(substring) # 输出:World
```
python格式化输出format3. 字符串拼接:
```python
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2
print(result) # 输出:Hello, World
```
4. 字符串查:
```python
my_string = "Hello, World!"
index = my_string.find("World")
print(index) # 输出:7
```
5. 字符串替换:
```python
my_string = "Hello, World!"
new_string = place("Hello", "Hi")
print(new_string) # 输出:Hi, World!
```
6. 字符串转换为小写或大写:
```python
my_string = "Hello, World!"
lower_case = my_string.lower()
upper_case = my_string.upper()
print(lower_case) # 输出:hello, world!
print(upper_case) # 输出:HELLO, WORLD!
```
7. 字符串去除首尾空格:
```python
my_string = " Hello, World! "
trimmed_string = my_string.strip()
print(trimmed_string) # 输出:Hello, World!
```
8. 字符串分割:
```python
my_string = "apple,banana,orange"
fruits = my_string.split(",")
print(fruits) # 输出:['apple', 'banana', 'orange']
```
9. 字符串格式化:
```python
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # 输出:My name is Alice and I am 25 years old.
```
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论