字符串常见的内建函数

本文介绍了Python中字符串的一些常用内置函数,包括首字母大写、全大写、全小写、长度计算、查找与替换、分割与连接、编码与解码、计数、去除空白以及判断开头和结尾等操作。这些函数对于处理字符串非常实用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串的首字母大写
str.capitalize()

s = 'hello world'
print(s.capitalize())
# 输出结果:
Hello world

字符串的每个单词首字母大写
str.title()

s = 'hello world'
print(s.title())
# 输出结果:
Hello World

带is
表示判断字符串的每个单词首字母是否是大写Ture
或False
str.istitle()

s = 'hello world'
print(s.istitle(), s)
s_title = s.title()
print(s_title.istitle(), s_title)

# 输出结果:
False hello world
True Hello World

将字符串里的每个字符都大写
str.upper()

s = 'hello world'
print(s.upper())
# 输出结果
HELLO WORLD

将字符串里的字母全部转成小写
str.lower()

s = 'HELLO WORLD'
print(s.lower())
# 输出结果
hello world

求字符串长度的函数
len(str)

s = 'hello world'
print(len(s))
# 输出结果
11

查找
rfind从右往左查找,find从左往右查找
find()

s = 'hello world'
print(s.find('w'))
print(s.find('s'))
# 输出结果
6  # 返回结果为查找目标的下标位置
-1  # 当没有找到目标时返回-1

print(s.find('o'), s.rfind('o'))
# 输出结果
4 7  # 分别对应hello里的o 和world里的o

使用index查找不到的时候的报错:ValueError: substring
not found
rindex从右往左查找,index从左往右查找
index()

s = 'hello world'
print(s.index('w'))  # 输出结果为6
print(s.index('s'))   
# 此时会报错,要查找的内容不存在
Traceback (most recent call last):
  File "D:/项目/Python基础练习文件/print_test.py", line 3, in <module>
    print(s.index('s'))
ValueError: substring not found

print(s.index('o'), s.rindex('o'))
# 输出结果
4 7  # 分别对应hello里的o 和world里的o

替换old表示旧内容,new表示新内容,max表示替换的次数,不填则全部替换
str.replace(old, new, max)

s = 'hello world'
print(s.replace('l', '*',))
print(s.replace('o', '-', 1))

# 输出结果:
he**o wor*d  # 将所有的l都替换成了*
hell- world  # 只替换了第一个查找到的o 替换为了-

查找字符串中含有分割符的位置,从分割符位置进行分割,可以指定分割次数,不填则默认全部分割
split(‘分隔符’, ‘分割次数’)

s = 'hello world'
print(s.split('o',))
print(s.split('l', 1))
# 输出结果:
['hell', ' w', 'rld']  # 查找所有的o
['he', 'lo world']

将字符串str以a连接起来(可以是字符串也可以是列表)
‘a‘.join(str)

s = 'hello world'
print('a'.join(s))
# 输出结果:
haealalaoa awaoaralad

encode()
汉字 - —>字节
decode()
字节 - ---->汉字
str.encode(‘utf-8’)
str.decode(‘utf-8’)

s = '你好'
print(s.encode('utf-8'))
# 输出结果:
b'\xe4\xbd\xa0\xe5\xa5\xbd'

print(b'\xe4\xbd\xa0\xe5\xa5\xbd'.decode())
# 输出结果:你好

个数
表示str里xxx的个数
str.count(‘xxx’)

s = 'hello world'
print(s.count('l'))
#输出结果:
3

"截掉字符串开头或结尾的空格或指定字符
lstrip
去头,rstrip
去尾,strip头和尾都去掉
" str.strip(‘s’) lstrip() rstrip()

s = 'aaaaasssssaaaaa'
print(s.strip('a'))
print(s.lstrip('a'))
print(s.rstrip('a'))
# 输出结果
sssss  # 去掉头部和尾部的所有a字符
sssssaaaaa  # 去掉头部的所有a字符
aaaaasssss  # 去掉尾部的所有a字符

判断字符串是否全部是字母
str.isalpha()

s = 'hello world'
s1 = 'helloworld'
print(s.isalpha())
print(s1.isalpha())
# 输出结果
False  # 字母只算a-zA-Z 空格、特殊符号、数字等都不算
True

判断字符串是否全部是数字
str.isdigit()

指定字符串长度,n为指定的长度,b为长度不足时指定在前方填充的内容 ,默认为空格
str.rjust(n, b)

s = 'hello world'
s1 = '1234567890'
print(s.rjust(15))
print(s.rjust(5))
# 输出结果
    hello world  # 指定长度大于字符串长度时 默认在字符串前面填充空格,补足相应长度
hello world  # 指定长度小于字符串长度时 默认返回全部字符串

自定义字符串中\t的长度,n为空格数量
str.expandtabs(n)

s = '\thello world'
s1 = '1234567890'
print(s)
print(s.expandtabs(8))

 # 输出结果
 	hello world
        hello world

判断字符串str是否以xxx开头,返回值True / False
str.startswith(‘xxx’)

s = 'hello world'
s1 = '1234567890'
print(s.startswith('h'))
print(s1.startswith('h'))

# 输出结果:
True
False

判断字符串str是否以xxx结尾,返回值True / False
str.endswith(‘xxx’)

s = 'hello world'
s1 = '1234567890'
print(s.endswith('d'))
print(s1.endswith('d'))

# 输出结果:
True
False
### Python 字符串内置函数概述 Python 提供了一系列丰富的字符串操作方法,这些方法可以直接用于处理字符串数据。以下是常见字符串内置函数及其功能说明: #### 基本字符串函数 - **`len(s)`**: 返回字符串 `s` 的长度[^2]。 ```python s = "hello" length = len(s) # 输出为5 ``` - **`find(sub, start=0, end=len(string))`**: 查找子字符串 `sub` 在字符串中的第一个位置,如果找不到则返回 `-1`。 ```python text = "hello world" position = text.find("world") # 输出为6 ``` - **`rfind(sub, start=0, end=len(string))`**: 类似于 `find()` 方法,但它会返回最后一次匹配到的索引位置。 ```python text = "banana" last_position = text.rfind("a") # 输出为5 ``` - **`index(sub, start=0, end=len(string))`**: 和 `find()` 功能相似,但如果未找到子字符串,则抛出异常。 ```python try: index_value = "abc".index("d") except ValueError as e: print(e) # 输出 'substring not found' ``` - **`rindex(sub, start=0, end=len(string))`**: 类似于 `index()`,但返回的是最后出现的位置。 --- #### 其他常用字符串函数 除了上述基本函数外,还有许多其他实用的方法可以用来操作字符串: - **`upper()`**: 将字符串转换成大写形式。 ```python result = "hello".upper() # 结果为'HELLO' ``` - **`lower()`**: 转换成小写形式。 ```python result = "HELLO".lower() # 结果为'hello' ``` - **`strip([chars])`**: 移除字符串两端的空白字符(默认为空格),也可以指定移除特定字符集合。 ```python cleaned_string = " hello ".strip() # 结果为'hello' custom_strip = "www.example.com".strip("wcom.") # 结果为'example' ``` - **`split(sep=None, maxsplit=-1)`**: 根据分隔符分割字符串并返回列表,默认按任意空白字符分割。 ```python words = "apple banana cherry".split() # ['apple', 'banana', 'cherry'] limited_split = "one,two,three,four".split(",", 2) # ['one', 'two', 'three,four'] ``` - **`join(iterable)`**: 使用当前字符串作为连接符来拼接可迭代对象中的元素。 ```python items = ["red", "green", "blue"] joined_text = ",".join(items) # 结果为'red,green,blue' ``` - **`replace(old, new[, count])`**: 替换字符串中的旧子串为新子串,可以选择替换次数。 ```python modified_text = "hello world".replace("world", "there") # 结果为'hello there' partial_replace = "ababa".replace("a", "A", 2) # 结果为'AbaBA' ``` --- #### 数字相关函数 虽然题目提到的内容主要涉及字符串,但也提到了一些通用数值型函数,例如: - **`abs(x)`**: 获取数字的绝对值[^1]。 ```python absolute_value = abs(-42) # 结果为42 ``` 以上列举了一些常用的字符串内置函数以及部分扩展内容,具体应用可以根据实际需求灵活组合使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值