一文掌握Python中字符串

liftword4个月前 (03-18)技术文章23

字符串连接

将字符串连接起来:

greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)

2. 使用str.format进行字符串格式化

将值插入到字符串模板中:

message = "{}, {}. Welcome!".format(greeting, name)
print(message)

3. 格式化字符串字面量(f-字符串)

在字符串字面量内嵌入表达式(Python 3.6+):

message = f"{greeting}, {name}. Welcome!"
print(message)

4. 字符串方法 — 大小写转换

将字符串的大小写进行更改:

s = "Python"
print(s.upper())  # Uppercase
print(s.lower())  # Lowercase
print(s.title())  # Title Case

5. 字符串方法 —strip、rstrip、lstrip

删除字符串两端空白或特定字符:

s = "   trim me   "
print(s.strip())   # Both ends
print(s.rstrip())  # Right end
print(s.lstrip())  # Left end

6. 字符串方法 —startswith、endswith

检查字符串的开始或结束位置是否存在特定文本:

s = "filename.txt"
print(s.startswith("file"))  # True
print(s.endswith(".txt"))    # True

7. 字符串方法 —split、join

将字符串拆分为列表或将列表连接成字符串:

s = "split,this,string"
words = s.split(",")        # Split string into list
joined = " ".join(words)    # Join list into string
print(words)
print(joined)

8. 字符串方法 —replace

将字符串的一部分替换为另一个字符串:

s = "Hello world"
new_s = s.replace("world", "Python")
print(new_s)

9. 字符串方法 —find、index

要查找子字符串在字符串中的位置:

s = "look for a substring"
position = s.find("substring")  # Returns -1 if not found
index = s.index("substring")    # Raises ValueError if not found
print(position)
print(index)

10. 字符串方法 — 处理字符

处理字符串中的单个字符:

s = "characters"
for char in s:
    print(char)  # Prints each character on a new line

11. 字符串方法 —isdigit、isalpha、isalnum

检查一个字符串是否只包含数字、字母或字母数字字符:

print("123".isdigit())   # True
print("abc".isalpha())   # True
print("abc123".isalnum())# True

12. 字符串切片

使用切片提取子字符串:

s = "slice me"
sub = s[2:7]  # From 3rd to 7th character
print(sub)

13. 字符串长度使用len

获取字符串长度:

s = "length"
print(len(s))  # 6

14. 多行字符串

与跨越多行的字符串一起工作:

multi = """Line one
Line two
Line three"""
print(multi)

15. 原始字符串

将反斜杠视为字面字符,这在正则表达式模式和文件路径中很有用:

path = r"C:\User\name\folder"
print(path)

相关文章

python 字符串的定义和表示

在Python中,字符串是一序列字符的集合。定义一个字符串可以使用单引号或双引号括起来的字符序列。下面是一些关于字符串的语法案例:字符串的定义和输出:# 使用单引号定义字符串 string1 = 'H...

Python 字符串

除了数字,Python还可以操作字符串。字符串的形式是单引号('......')双引号(''.........'')或三个单引号('''..........''')>>> 'spam...

「Python字符串类型」文档字符串使用

功能要求编写一个Python应用程序,定义一个函数,在函数中使用文档字符串,并通过__doc__成员进行查看;使用help()函数查看。实现步骤1.创建一个Python文件,通过__doc__成员进行...

Python字符串详细介绍

上一篇文章介绍了列表、元组和字符串等数据类型。本章详细介绍字符串。1. 字符串的表示方式:1.1 普通字符串普通字符串指用单引号(')或双引号(")括起来的字符串。如果想在字符串中包含一些特殊的字符,...

Python基础——格式化字符串的三种方式

格式化字符串其实就是字符串的拼接普通的字符串拼接:下边介绍3种python的格式化字符串的方法方法一使用格式化操作符%进行对字符串进行格式化常用的操作符有:符号含义%s格式化字符串%d格式化整数%f格...