Python字符串详解与示例

createh510小时前技术教程5

艾瑞巴蒂字符串的干货来了,

字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍

下字符串的特性,操作和方法,和一些示例来吧道友:

1. 字符串的创建

在python中字符串可以永单引号(' ')双引号(" ")和或三引号(''' '''或""" """)来创建。

# 单引号字符串
str1 = 'Hello, World!'

# 双引号字符串
str2 = "Python Programming"

# 三引号字符串(可以跨多行)
str3 = '''This is a 
multi-line 
string.'''

print(str1)
print(str2)
print(str3)

2. 字符串的基本操作

访问子串串的字符

s = "Python"
print(s[0])  # 输出: 'P' (第一个字符)
print(s[-1]) # 输出: 'n' (最后一个字符)

字符串切片(字符提取可以这么理解)

s = "Programming"
print(s[0:4])   # 输出: 'Prog' (索引0到3)
print(s[3:])    # 输出: 'gramming' (从索引3到最后)
print(s[:6])    # 输出: 'Progra' (从开始到索引5)
print(s[-5:-2]) # 输出: 'mmi' (倒数第5到倒数第3)
print(s[::2])   # 输出: 'Pormig' (每隔一个字符)

字符串连接(+号链接)

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)  # 输出: 'Hello World'

字符串重复(*号后面加重复次数)

s = "Hi"
print(s * 3)  # 输出: 'HiHiHi'

3. 字符串常用方法

查找方法

s = "Python Programming"

# find() - 返回子字符串的起始索引,找不到返回-1
print(s.find("Pro"))  # 输出: 7
print(s.find("Java")) # 输出: -1

# index() - 类似find(),但找不到会抛出异常
print(s.index("Pro")) # 输出: 7

# count() - 统计子字符串出现次数
print(s.count("m"))   # 输出: 2

修改方法 (大小写,替换)

s = "  hello world  "

# lower()和upper()
print(s.upper())      # 输出: '  HELLO WORLD  '
print(s.lower())      # 输出: '  hello world  '

# strip() - 去除两端空白
print(s.strip())      # 输出: 'hello world'

# replace() - 替换子字符串
print(s.replace("world", "Python"))  # 输出: '  hello Python  '

# split() - 分割字符串
print("apple,banana,orange".split(","))  # 输出: ['apple', 'banana', 'orange']

检查方法

s = "Python123"

# isalpha() - 是否全是字母
print(s.isalpha())    # 输出: False

# isdigit() - 是否全是数字
print("123".isdigit()) # 输出: True

# isalnum() - 是否只包含字母和数字
print(s.isalnum())    # 输出: True

# startswith()和endswith()
print(s.startswith("Py"))  # 输出: True
print(s.endswith("23"))    # 输出: True

4. 字符串格式化 三种格式

% 格式化 (旧式)

name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))

str.format() 方法

name = "Bob"
age = 30
print("My name is {} and I'm {} years old.".format(name, age))
print("My name is {1} and I'm {0} years old.".format(age, name))

f-strings (Python 3.6+)

name = "Charlie"
age = 35
print(f"My name is {name} and I'm {age} years old.")
print(f"Next year I'll be {age + 1} years old.")

5. 字符串的转义字符

print("Line1\nLine2")  # 换行
print("Tab\tseparated")  # 制表符
print("This is a backslash: \\")  # 反斜杠
print("She said, \"Hello!\"")  # 双引号
print('It\'s raining')  # 单引号

6. 字符串不可变性

字符串是不可变的,意味着不能直接修改字符串中的某个字符

s = "hello"
# s[0] = 'H'  # 这会报错

# 正确的方法是创建新字符串
s = 'H' + s[1:]
print(s)  # 输出: 'Hello'

7. 字符串编码

# 编码为字节
s = "你好"
b = s.encode('utf-8')
print(b)  # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd'

# 解码回字符串
s2 = b.decode('utf-8')
print(s2)  # 输出: '你好'

8. 字符串其他有用方法

# join() - 连接序列中的字符串
words = ["Python", "is", "great"]
print(" ".join(words))  # 输出: 'Python is great'

# partition() - 分割字符串为三部分
print("python.is.cool".partition("."))  # 输出: ('python', '.', 'is.cool')

# zfill() - 用零填充字符串
print("42".zfill(5))  # 输出: '00042'

以上为字符串的常用操作,掌握这基本操作你就张了个翅膀!

多练才是王道,初学着几天不看全忘完!

老板点个赞加收藏呗

相关文章

在 JavaScript 中替换所有指定字符 3 种方法

在 JS 没有提供一种简便的方法来替换所有指定字符。 在 Java 中有一个 replaceAll() ,replaceAll(String regex, String replacement))方法...

在Java中实现字符串的动态替换

比如消息通知,短信发送之类的我们肯定是要用到字符串模版的替换的要在Java中实现字符串的动态替换,可以使用String.format方法或者MessageFormat类或者三方包。以下是使用这三种方法...

正则表达式学习之替换分组练习

切割案例小练习:字符串77 23 91 99 31 排序输出23 31 77 91 99分析:1、 字符切割数组2、 字符数组转换成数字数组3、 排序4、 遍历拼接字符串代码结果替换案例小练习字符串:...

Shell语言搜索路径、字符串替换、易用性

若文章对您有帮助,欢迎关注 程序员小迷 。助您在编程路上越走越好!Shell为了方便操作内核,一般为动态、弱类型语言。变量不管是什么类型,本质都是字符串,根据实际情况做转换。字符串替换新产品升级有时就...

Java面试“字符串三兄弟”String、StringBuilder、StringBuffer

Java面试中的“字符串三兄弟”:String、StringBuilder与StringBuffer在Java的世界里,字符串是一个非常重要的数据类型。而在众多的字符串操作类中,String、Stri...

漫画:腾讯面试题,请实现把字符串中的空格替换为“%20”

面试现场题目描述请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。import java.u...