python 中字符串的用法
时间: 2023-09-24 16:06:23 浏览: 121
Python中字符串对齐方法介绍
5星 · 资源好评率100%
Python中的字符串可以使用单引号、双引号、三引号来定义,例如:
```
str1 = 'hello world'
str2 = "hello world"
str3 = '''hello
world'''
```
字符串也支持拼接、切片、替换、查找等操作,例如:
```
str1 = "hello"
str2 = "world"
print(str1 + " " + str2) # 拼接
str = "hello world"
print(str[0]) # 切片
print(str[2:5])
str = "hello world"
print(str.replace("world", "python")) # 替换
str = "hello world"
if "world" in str: # 查找
print("Yes")
else:
print("No")
```
同时,Python中字符串还支持格式化输出,例如:
```
name = "John"
age = 28
print("My name is %s, and I am %d years old." % (name, age))
```
输出结果为:`My name is John, and I am 28 years old.`
阅读全文