python的字符串方法举例

Python中的字符串对象提供了许多内置的方法,用于操作和处理字符串。以下是一些常用的字符串方法及其示例:

1. split()

将字符串分割为子字符串列表,并返回该列表。

s = "Hello World"
words = s.split()  # 默认按空格分割
print(words)  # 输出: ['Hello', 'World']

# 也可以指定分隔符
s = "apple,banana,cherry"
fruits = s.split(",")
print(fruits)  # 输出: ['apple', 'banana', 'cherry']

2. strip(), lstrip(), rstrip()

去除字符串两侧的空白字符(包括空格、换行符、制表符等)。

s = "   Hello World   "
trimmed = s.strip()
print(trimmed)  # 输出: 'Hello World'

# 仅去除左侧空白字符
left_trimmed = s.lstrip()
print(left_trimmed)  # 输出: 'Hello World   '

# 仅去除右侧空白字符
right_trimmed = s.rstrip()
print(right_trimmed)  # 输出: '   Hello World'

3. upper(), lower()

将字符串转换为大写或小写。

s = "Hello"
upper_s = s.upper()
print(upper_s)  # 输出: 'HELLO'

lower_s = s.lower()
print(lower_s)  # 输出: 'hello'

4. replace()

替换字符串中的某些字符或子字符串。

s = "Hello World"
new_s = s.replace("World", "Python")
print(new_s)  # 输出: 'Hello Python'

5. find(), index()

查找子字符串在字符串中首次出现的位置。如果未找到,则返回-1。

s = "Hello World"
position = s.find("World")
print(position)  # 输出: 6

# index() 方法与 find() 类似,但找不到子字符串时会抛出异常
try:
    position = s.index("Python")
except ValueError:
    print("Substring not found")

6. startswith(), endswith()

检查字符串是否以指定的前缀或后缀开始或结束。

s = "Hello World"
starts = s.startswith("Hello")
print(starts)  # 输出: True

ends = s.endswith("World")
print(ends)  # 输出: True

7. join()

使用指定的分隔符将序列的元素连接成一个字符串。

words = ["Hello", "World"]
s = " ".join(words)
print(s)  # 输出: 'Hello World'

8. isalpha(), isdigit(), isalnum()

检查字符串是否只包含字母、数字或字母数字字符。

s = "abc123"
is_alpha = s.isalpha()  # 只包含字母
print(is_alpha)  # 输出: False

is_digit = s.isdigit()  # 只包含数字
print(is_digit)  # 输出: False

is_alnum = s.isalnum()  # 包含字母和数字
print(is_alnum)  # 输出: True

9. format()

格式化字符串,插入变量或表达式的结果。

name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)  # 输出: 'My name is Alice and I am 30 years old.'

这些只是Python字符串方法的一部分,字符串对象还提供了许多其他方法和属性,可以根据具体需求选择使用。

posted @   nxhujiee  阅读(103)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示