当处理字符串时,Python提供了许多内置函数和方法,以便进行各种字符串操作。
一、对字符串使用=和==运算符
1.1 初始化
在Python中,可以使用等号(=)将一个字符串赋值给一个变量,以便在后续的代码中使用。这将创建一个变量,它引用或存储字符串的值。例如:
my_string = "Hello, World"
在上面的示例中,my_string 是一个变量,它被赋值为字符串 “Hello, World”。
1.2 赋值
可以使用等号将不同的字符串赋给同一个变量,从而更改变量的值。例如:
my_string = "Hello"
print(my_string) # 输出:Hello
my_string = "World"
print(my_string) # 输出:World
1.3 判断是否相等
还可以使用等号来比较两个字符串是否相等。例如:
str1 = "Hello"
str2 = "World"
if str1 == str2:
print("Strings are equal")
else:
print("Strings are not equal")
在这个示例中,由于 str1 和 str2 不相等,因此输出是 “Strings are not equal”。
总之,等号在Python中可以用于赋值和比较字符串。
二、字符串的访问
2.1 索引访问
索引从0开始。
Python语言中包括两种序号体系:正向递增序号和反向递减序号。
>>> s = 'hello world'
>>> s[0] # 访问索引为0的元素,即第一个元素
'h'
>>> s[1] # 访问索引为1的元素,即第二个元素
'e'
>>> s[-1] # 访问最后一个元素
'd'
>>> s[-2] # 访问倒数第二个元素
'l'
2.2 切片访问
具体语法格式为:【头下标:尾下标】,尾下标的元素取不到。
这种访问方式称之为“切片”。但注意这是左闭右开的区间。在切片方式中,若头下标缺省,表示从字符串的开始取子串;若尾下标缺省,表示取到字符串的最后一个字符;若头下标和尾下标都缺省,则取整个字符串。
>>> s = 'hello world'
>>> s[0:5]
'hello'
>>> s
'hello world'
>>> s[:6]
'hello '
>>> s[6:]
'world'
>>> s[6:-1]
'worl'
>>> s[:]
'hello world'
三、字符串拼接
可以使用+运算符将两个字符串拼接在一起。
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2
print(result) # 输出:Hello, World
四、字符串重复
使用*运算符可以重复一个字符串。
str1 = "Python"
result = str1 * 3
print(result) # 输出:PythonPythonPython
五、获取字符串长度
可以使用len()函数来获取字符串的长度。
str1 = "Python"
length = len(str1)
print(length) # 输出:6
六、字符串格式化
[[输入输出]]
字符串格式化允许你创建具有占位符的字符串,并用值替换这些占位符。你可以使用format()方法或f-strings(Python 3.6+)来格式化字符串。
使用format()方法:
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # 输出:My name is Alice and I am 30 years old.
使用f-strings(推荐):
name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message) # 输出:My name is Alice and I am 30 years old.
七、字符串拆分
你可以使用split()方法将字符串拆分为子字符串,返回一个列表。默认情况下,它使用空格来拆分。
text = "Hello, World"
words = text.split()
print(words) # 输出:['Hello,', 'World']
你还可以指定分隔符来拆分字符串:
text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits) # 输出:['apple', 'banana', 'cherry']
八、字符串替换
使用replace()方法来替换字符串中的子字符串,将所有子字符串(_old)都替换成新字符串(_new)。
text = "Hello, World"
new_text = text.replace("l", "!jyt!")
print(new_text) # 输出:He!jyt!!jyt!o, Wor!jyt!d
九、字符串查找
你可以使用find()或index()方法来查找子字符串的位置。它们返回子字符串在原字符串中的索引。如果找不到,find()返回-1,而index()引发一个异常->ValueError。
text = "Hello, World"
position = text.find("World")
print(position) # 输出:7
十、其他常用操作
10.1 大小写转换
使用upper()和lower()方法将字符串转换为大写或小写。
text = "Hello, World"
upper_text = text.upper()
lower_text = text.lower()
print(upper_text) # 输出:HELLO, WORLD
print(lower_text) # 输出:hello, world
10.2 判断大小写
单个字符调用isupper()、islower()、isdigit()函数,判断是否是大写字母、小写字母、数字。
若想判断整个字符串,可以写入循环。
[[Python/Python课程/希冀平台/第二次作业:函数]]中的Task_3:
def is_valid_password(password):
if len(password) < MIN_LENGTH or len(password) > MAX_LENGTH:
return False
has_uppercase = False
has_lowercase = False
has_numbers = False
for char in password:
if char.isupper():
has_uppercase = True
if char.islower():
has_lowercase = True
if char.isdigit():
has_numbers = True
if has_numbers and has_lowercase and has_uppercase:
return True
else:
return False
10.3 去换行符
从文件中读取的字符串常常带有 /n ,用字符串.strip()去除末尾的换行。
with open("names.txt") as file:
name_list = file.read().strip().split(',') # 读取+去换行符+拆分为列表
capital_list = []
lowercase_list = []
for i in name_list:
temp = i[0]
for char in i[1:]:
if char.isupper(): # 逐个字符判断大写
temp += char
capital_list.append(temp)
lowercase_list.append(i.lower()) # 整个字符串转化为小写
print(capital_list)
print(lowercase_list)
10.4 join()
join() 方法是字符串对象的一个方法,用于将序列中的元素以指定的字符串连接生成一个新的字符串。这个方法通常用于将列表中的元素拼接成一个字符串。
语法:
string.join(iterable)
string: 这是连接的字符串,即用来将序列中的元素连接起来的字符串。iterable: 这是要连接的元素序列,通常是列表或元组。
示例:
1. 使用空格连接字符串列表:
words = ["Hello", "World", "Python"]
result = " ".join(words)
print(result)
# 输出: Hello World Python
2. 使用逗号连接元组中的元素:
numbers = ("One", "Two", "Three")
result = ",".join(numbers)
print(result)
# 输出: One,Two,Three
3. 使用换行符连接文本行:
lines = ["Line 1", "Line 2", "Line 3"]
result = "\n".join(lines)
print(result)
# 输出:
# Line 1
# Line 2
# Line 3
4. 使用空字符串连接字符:
characters = ["a", "b", "c", "d"]
result = "".join(characters)
print(result)
# 输出: abcd
join() 方法提供了一种方便的方式将序列中的元素连接为一个字符串。在拼接字符串时,你可以指定连接的字符串是什么,比如空格、逗号、换行符等。这对于构建特定格式的字符串非常有用。
10.5 title()
在 Python 中,title() 是字符串对象的一个方法,用于将字符串中每个单词的首字母大写,其余字母小写,返回一个新的字符串。
语法:
string.title()
示例:
text = "hello world, python"
result = text.title()
print(result)
# 输出: Hello World, Python
在这个例子中,title() 方法将字符串中的每个单词的首字母大写,其余字母小写,得到了一个新的字符串。
请注意,title() 并不会更改原始字符串,而是返回一个新的字符串。如果你想在原地修改字符串,可以将结果赋值回原始变量:
text = "hello world, python"
text = text.title()
print(text)
# 输出: Hello World, Python
这个方法在需要规范化字符串中的标题或标签时很有用。
本文详细介绍了Python中字符串的基本操作,如赋值、比较、索引和切片、拼接、重复、长度计算、格式化、拆分、替换、查找、大小写转换、去除换行、join和title方法。
965

被折叠的 条评论
为什么被折叠?



