龙空技术网

Python字符串函数总结

大马猴233333 88

前言:

现时姐妹们对“pythonlen字符串长度怎么算”都比较关心,我们都需要了解一些“pythonlen字符串长度怎么算”的相关文章。那么小编在网络上搜集了一些对于“pythonlen字符串长度怎么算””的相关文章,希望看官们能喜欢,各位老铁们快快来学习一下吧!

字符串创建字符串字面量:通过单引号(')、双引号(")或三引号(''' 或 """)创建字符串。

str1 = 'Hello'str2 = "World"str3 = '''This is a multi-line string'''
基本字符串操作len(): 获取字符串的长度。
s = "hello"length = len(s)  # 5
str(): 将其他类型转换为字符串。
num = 123s = str(num)  # "123"
字符串方法1. 大小写转换

lower(): 将字符串转换为小写。

s = "HELLO"s_lower = s.lower()  # "hello"

upper(): 将字符串转换为大写。

s = "hello"s_upper = s.upper()  # "HELLO"

capitalize(): 将字符串的第一个字符转换为大写。

s = "hello"s_cap = s.capitalize()  # "Hello"

title(): 将字符串的每个单词的首字母转换为大写。

s = "hello world"s_title = s.title()  # "Hello World"

swapcase(): 将字符串的大小写互换。

s = "Hello World"s_swap = s.swapcase()  # "hELLO wORLD"
2. 查找和替换

find(): 查找子字符串在字符串中首次出现的位置,找不到返回 -1。

s = "hello"index = s.find('e')  # 1

rfind(): 查找子字符串在字符串中最后一次出现的位置,找不到返回 -1。

s = "hello"index = s.rfind('l')  # 3

index(): 查找子字符串在字符串中首次出现的位置,找不到会引发 ValueError。

s = "hello"index = s.index('e')  # 

rindex(): 查找子字符串在字符串中最后一次出现的位置,找不到会引发 ValueError。

s = "hello"index = s.rindex('l')  # 3

replace(): 将字符串中的子字符串替换为新的子字符串。

s = "hello world"new_s = s.replace("world", "Python")  # "hello Python"
3. 拆分和连接

split(): 以指定分隔符拆分字符串,返回一个列表。

s = "a,b,c"parts = s.split(',')  # ['a', 'b', 'c']

rsplit(): 从右侧开始以指定分隔符拆分字符串,返回一个列表。

s = "a,b,c"parts = s.rsplit(',', 1)  # ['a,b', 'c']

splitlines(): 以换行符拆分字符串,返回一个列表。

s = "hello\nworld"lines = s.splitlines()  # ['hello', 'world']

join(): 使用指定分隔符将列表中的元素连接成一个字符串。

parts = ['a', 'b', 'c']s = ','.join(parts)  # "a,b,c"
4. 去除空白字符

strip(): 去除字符串两端的空白字符。

s = "  hello  "stripped_s = s.strip()  # "hello"

lstrip(): 去除字符串左端的空白字符。

s = "  hello  "lstripped_s = s.lstrip()  # "hello  "

rstrip(): 去除字符串右端的空白字符。

s = "  hello  "rstripped_s = s.rstrip()  # "  hello"
5. 判断字符串特性

startswith(): 判断字符串是否以指定子字符串开头。

s = "hello"result = s.startswith("he")  # True

endswith(): 判断字符串是否以指定子字符串结尾。

s = "hello"result = s.endswith("lo")  # True

isalpha(): 判断字符串是否只包含字母。

s = "hello"result = s.isalpha()  # True

isdigit(): 判断字符串是否只包含数字。

s = "12345"result = s.isdigit()  # True

isalnum(): 判断字符串是否只包含字母和数字。

s = "hello123"result = s.isalnum()  # True

isspace(): 判断字符串是否只包含空白字符。

s = "   "result = s.isspace()  # True

istitle(): 判断字符串是否是标题格式(每个单词首字母大写)。

s = "Hello World"result = s.istitle()  # True

islower(): 判断字符串是否全为小写。

s = "hello"result = s.islower()  # True

isupper(): 判断字符串是否全为大写。

s = "HELLO"result = s.isupper()  # True
6. 格式化字符串

format(): 使用花括号 {} 和 : 进行字符串格式化。

s = "Hello, {}!".format("world")  # "Hello, world!"

f-strings: 使用 f 前缀和花括号 {} 进行字符串格式化(Python 3.6+)。

name = "world"s = f"Hello, {name}!"  # "Hello, world!"

标签: #pythonlen字符串长度怎么算