python中的字符串方法

python中的字符串

举个例子先
python 复制代码
name = '貂蝉开大'  #声明了一个字符串
print(name) # 打印了一个字符串
print(name[0:1]  #输出貂蝉
print(name[2:3]  #输出开大
扩展方法
find()
python 复制代码
# 查找字符串中某个字符的索引
index_ = name.find("貂")
print(index_)   # 输出 0
title()
python 复制代码
# 将字符串首字母大写
diaochan = 'diaoChan'
new_name = diaochan.title();
print(new_name) # 'DiaoChan'
upper()
python 复制代码
# 将字符串全部大写 
name = 'diaochankaida'
name_ = name.upper();
print(name_)  #'DIAOCHANKAIDA'
lower()
python 复制代码
#将字符串全部小写
name = 'ABCD'
new_name = name.lower()
print(new_name)  # 'abcd'
count()
python 复制代码
# 计算某个子串在字符串中出现的次数,可以指定开始和结束
name = 'aaaabbbbsdddekkkk'
num_a = name.count('a');
print(num_a) # 4
endswith()和startwith()
python 复制代码
# 返回一个布尔值True 或 False
# string.endswith(suffix[, start[, end]])
# string.startswith(suffix[, start[, end]])
str_ = 'hello,pete'
print(str.endswith('a'),2,4)  # False
print(str.startswith('h'))  # True
find() & rfind() & index() & rindex()
python 复制代码
# rfind() 和 rindex() 都是用于在一个字符串中寻找某个子串最后一次出现的位置的方法,rfind未找到返回-1,不会抛出异常,rindex未找到会抛出异常ValueError
# rfind(sub[, start[, end]])
# rindex(sub[, start[, end]])

#find(),index()是从左到右搜索,而rfind(),rfind()是从右到左搜索。

s = "hello world"
print(s.rfind("o"))  # 输出: 7,因为"o"在"world"中最后的位置是7
print(s.rfind("Python"))  # 输出: -1,因为"Python"不在s中

try:
    print(s.rindex("o"))  # 输出: 7,同上
except ValueError:
    pass
replace()
python 复制代码
# my_str.replace(old, new[, count])
# 将字符串中的 old 替换为 new 字符串,如果给定 count,则表示只替换前 count 个 old 子串。

text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)  # 输出: Hello, Python!
split()、rsplit()和 splitlines()
python 复制代码
my_str.split(sep=None, maxsplit=-1)
my_str.rsplit(sep=None, maxsplit=-1)
my_str.splitlines([keepends=True])

#  split() 根据 sep 对 my_str 进行分割,maxsplit用于指定分割次数。

#  splitlines() 用来分割换行符。

# split(): 这个方法默认按空格进行分割,并返回由子字符串组成的列表。例子如下:
sentence = "Hello, World! This is a test."
words = sentence.split()
print(words)  # ["Hello,", "World!", "This", "is", "a", "test."]
# 可以通过传递参数给split()指定其他分隔符,如逗号 , 或者自定义字符。

#rsplit(): 类似于split(), 但是从字符串的右端开始分割。例如:
reversed_words = "Hello, World! This is a test.".rsplit(',')
print(reversed_words)  # ["Hello, World! This is a test", ""]

#splitlines(): 主要用于文本文件的处理,它会根据行结束符(\n, \r\n等)自动分隔成多行。默认情况下,它会保留每行的换行符。例如:
lines = "Hello\nWorld\nThis\nIs a test".splitlines()
print(lines)  # ["Hello", "World", "This", "Is a test"]
# 可以通过参数keepends=True来保留换行符:
lines_with_newlines = "Hello\nWorld\nThis\nIs a test".splitlines(keepends=True)
print(lines_with_newlines)  # ["Hello\n", "World\n", "This\n", "Is a test"]
join()
python 复制代码
# 它用于将序列(如列表或元组)中的元素连接成一个新的字符串,每个元素之间由指定的分隔符连接。例如:
#  my_str.join(iterable)
words = ['Hello', 'world', '!']
sentence = '-'.join(words)
print(sentence)  # 输出 "Hello-world-!"
strip()、lstrip()和 rstrip()
python 复制代码
# strip() 函数:去除字符串两端的空白字符(包括空格、制表符、换页符等)。如果需要保留开头或结尾的特定字符,可以使用 lstrip() 或 rstrip() 分别去除左边或右边的空白:

s = " Hello World "
clean_s = s.strip()
print(clean_s)  # 输出 "Hello World"

s = "   Hello World   "
clean_s = s.lstrip()
print(clean_s)  # 输出 "Hello World   "

s = "Hello World   "
clean_s = s.rstrip()
print(clean_s)  # 输出 "Hello World"
字符串格式化

字符串格式化有三种方式,分别为 % 占位符格式化,format() 方法格式化,以及 f-string

python 复制代码
#% 占位符格式化(旧式方法):这种方法通过在字符串中使用 % 符号配合元组或字典来替换变量值。例如:
name = "Alice"
age = 25
format_string = "My name is %s and I am %d years old."
formatted = format_string % (name, age)
print(formatted)  # 输出 "My name is Alice and I am 25 years old."

#str.format() 方法格式化:这是一种更现代、更易读的格式化方式。使用花括号 {} 包围变量名,然后传入一个包含键值对的字典:
data = {"name": "Bob", "age": 30}
formatted_str = "My name is {} and I am {} years old.".format(data["name"], data["age"])
print(formatted_str)  # 输出 "My name is Bob and I am 30 years old."

#f-string(格式化字符串字面量):这是 Python 3.6 及以后版本引入的一种新的字符串格式化方法,直接在字符串前加上 f 或 F 开头,使用大括号内嵌表达式:
name = "Charlie"
age = 40
formatted = f"My name is {name} and I am {age} years old."
print(formatted)  # 输出 "My name is Charlie and I am 40 years old."

#各种方法各有特点,f-string 更简洁直观,而旧式方法和 str.format() 更适合复杂格式化需求。
相关推荐
重生之我在20年代敲代码16 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文18 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
waterHBO1 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286113 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py3 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy3 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
C-SDN花园GGbond5 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法