Python中字符串常见方法

在 Python 中,字符串 (str) 是一种非常常用的数据类型,提供了丰富的内置方法来处理和操作字符串。下面我将介绍一些常用的字符串方法,并附上示例。

1. lower()upper()

  • lower():将字符串中的所有字符转换为小写。
  • upper():将字符串中的所有字符转换为大写。
示例:
s = "Hello World"
print(s.lower())  # 输出: 'hello world'
print(s.upper())  # 输出: 'HELLO WORLD'

2. strip()

  • strip():去掉字符串两端的空白字符(包括空格、制表符、换行符等)。
  • lstrip():去掉字符串左边的空白字符。
  • rstrip():去掉字符串右边的空白字符。
示例:
s = "  Hello World  "
print(s.strip())   # 输出: 'Hello World'
print(s.lstrip())  # 输出: 'Hello World  '
print(s.rstrip())  # 输出: '  Hello World'

3. split()join()

  • split(sep=None, maxsplit=-1):根据分隔符 sep 分割字符串,返回一个列表。如果没有指定 sep,则默认按空白字符分割。
  • join(iterable):将一个可迭代对象(如列表)中的元素连接成一个字符串,元素之间使用指定的分隔符。
示例:
s = "apple,banana,cherry"
print(s.split(','))  # 输出: ['apple', 'banana', 'cherry']

lst = ['apple', 'banana', 'cherry']
print('-'.join(lst))  # 输出: 'apple-banana-cherry'

4. replace()

  • replace(old, new, count=-1):返回一个新的字符串,将原字符串中所有的 old 子串替换为 new 子串,count 表示替换的次数(默认为无限制)。
示例:
s = "apple apple apple"
print(s.replace('apple', 'orange'))  # 输出: 'orange orange orange'
print(s.replace('apple', 'orange', 2))  # 输出: 'orange orange apple'

5. find()index()

  • find(sub):返回子字符串 sub 在字符串中的最低索引位置,如果未找到则返回 -1。
  • index(sub):返回子字符串 sub 在字符串中的最低索引位置。如果未找到会抛出 ValueError 异常。
示例:
s = "hello world"
print(s.find('world'))  # 输出: 6
print(s.index('world')) # 输出: 6
print(s.find('python')) # 输出: -1
# print(s.index('python')) # 会抛出 ValueError: substring not found

6. startswith()endswith()

  • startswith(prefix):检查字符串是否以 prefix 开头,返回布尔值。
  • endswith(suffix):检查字符串是否以 suffix 结尾,返回布尔值。
示例:
s = "hello world"
print(s.startswith('hello'))  # 输出: True
print(s.endswith('world'))   # 输出: True
print(s.startswith('world')) # 输出: False

7. isalpha()isdigit()

  • isalpha():检查字符串是否只包含字母(a-zA-Z),并且至少有一个字符。
  • isdigit():检查字符串是否只包含数字字符,并且至少有一个字符。
示例:
s = "Hello"
print(s.isalpha())  # 输出: True
print(s.isdigit())  # 输出: False

s2 = "12345"
print(s2.isalpha())  # 输出: False
print(s2.isdigit())  # 输出: True

8. len()

  • len():返回字符串的长度(字符的个数)。
示例:
s = "hello"
print(len(s))  # 输出: 5

9. count()

  • count(sub):返回子字符串 sub 在字符串中出现的次数。
示例:
s = "apple apple orange apple"
print(s.count('apple'))  # 输出: 3

10. format()

  • format():格式化字符串,允许在字符串中插入变量的值。
示例:
name = "Alice"
age = 25
s = "My name is {} and I am {} years old.".format(name, age)
print(s)  # 输出: 'My name is Alice and I am 25 years old.'

11. zfill(width)

  • zfill(width):返回一个宽度为 width 的字符串,如果原字符串长度不足 width,则用 0 填充。
示例:
s = "42"
print(s.zfill(5))  # 输出: '00042'

12. capitalize()title()

  • capitalize():将字符串的第一个字符转换为大写,其他字符转换为小写。
  • title():将字符串中的每个单词的首字母转换为大写。
示例:
s = "hello world"
print(s.capitalize())  # 输出: 'Hello world'
print(s.title())       # 输出: 'Hello World'

13. isupper()islower()

  • isupper():检查字符串中的所有字符是否都为大写字母。
  • islower():检查字符串中的所有字符是否都为小写字母。
示例:
s = "HELLO"
print(s.isupper())  # 输出: True
print(s.islower())  # 输出: False

s2 = "hello"
print(s2.isupper()) # 输出: False
print(s2.islower()) # 输出: True

14. swapcase()

  • swapcase():将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。
示例:
s = "Hello World"
print(s.swapcase())  # 输出: 'hELLO wORLD'

15. expandtabs(tabsize=8)

  • expandtabs():将字符串中的所有制表符 (\t) 替换为适当数目的空格,默认是 8 个空格。
示例:
s = "hello\tworld"
print(s.expandtabs(4))  # 输出: 'hello   world'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值