Python 字符串常用方法详解 (15个实例)

本文将详细介绍 Python 中 15 个常用的字符串方法,并辅以示例代码,帮助你快速掌握字符串操作技巧。

  1. len(): 返回字符串的长度。
string = 'Hello World'
length = len(string)
print(length)  # 输出: 11
  1. lower(): 将字符串中的字母转换为小写。
string = 'Hello World'
lower_string = string.lower()
print(lower_string)  # 输出: hello world
  1. upper(): 将字符串中的字母转换为大写。
string = 'Hello World'
upper_string = string.upper()
print(upper_string)  # 输出: HELLO WORLD
  1. capitalize(): 将字符串的首字母转换为大写,其他字母转换为小写。
string = 'hello world'
capitalized_string = string.capitalize()
print(capitalized_string)  # 输出: Hello world
  1. replace(): 将字符串中的一个子串替换为另一个字符串。
string = 'Hello World'
replaced_string = string.replace('World', 'Python')
print(replaced_string)  # 输出: Hello Python
  1. split(): 将字符串按照指定的分隔符分割成多个子串,并返回一个列表。
string = 'Hello, World!'
split_string = string.split(',')
print(split_string)  # 输出: ['Hello', ' World!']
  1. strip(): 去除字符串两端的空格或指定的字符。
string = '  Hello World  '
stripped_string = string.strip()
print(stripped_string)  # 输出: Hello World
  1. find(): 查找字符串中某个子串第一次出现的位置。
string = 'Hello World'
index = string.find('World')
print(index)  # 输出: 6
  1. isalnum(): 判断字符串是否只包含字母和数字。
string1 = 'Hello123'
string2 = 'Hello World'
print(string1.isalnum())  # 输出: True
print(string2.isalnum())  # 输出: False
  1. isalpha(): 判断字符串是否只包含字母。
string1 = 'Hello'
string2 = 'Hello123'
print(string1.isalpha())  # 输出: True
print(string2.isalpha())  # 输出: False
  1. isdigit(): 判断字符串是否只包含数字。
string1 = '123'
string2 = 'Hello123'
print(string1.isdigit())  # 输出: True
print(string2.isdigit())  # 输出: False
  1. join(): 将多个字符串拼接成一个字符串。
strings = ['Hello', 'World']
joined_string = ' '.join(strings)
print(joined_string)  # 输出: Hello World
  1. count(): 统计字符串中某个子串出现的次数。
string = 'Hello World, Hello Python'
count = string.count('Hello')
print(count)  # 输出: 2
  1. startswith(): 判断字符串是否以指定的子串开头。
string = 'Hello World'
print(string.startswith('Hello'))  # 输出: True
print(string.startswith('World'))  # 输出: False
  1. endswith(): 判断字符串是否以指定的子串结尾。
string = 'Hello World'
print(string.endswith('World'))  # 输出: True
print(string.endswith('Hello'))  # 输出: False

希望本文对你学习 Python 字符串方法有所帮助! 如果你还有其他疑问,欢迎在评论区留言。

Python 字符串常用方法详解 (15个实例)

原文地址: http://www.cveoy.top/t/topic/qwRD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录