python字符串的用法
python字符串的用法
Python 中的字符串是不可变的序列,用于表示文本数据。字符串可以用单引号 ‘、双引号 " 或三引号 ‘’’ 或 “”" 来定义。以下是一些常见的字符串用法和操作:
1. 创建字符串
s1 = 'Hello, World!'
s2 = "Python is fun"
s3 = '''This is a multi-line
string in Python.'''
s4 = """Another multi-line
string example."""
2. 字符串拼接
可以使用 + 运算符来拼接字符串:
s1 = "Hello"
s2 = "World"
s = s1 + ", " + s2 + "!"
print(s) # 输出: Hello, World!
3. 字符串重复
使用 * 运算符可以重复字符串:
s = "Python " * 3
print(s) # 输出: Python Python Python
4. 字符串索引和切片
字符串中的每个字符都有一个索引,索引从 0 开始。可以使用索引访问单个字符,或使用切片访问子字符串:
s = "Python"
print(s[0]) # 输出: P
print(s[-1]) # 输出: n (负索引表示从末尾开始)
print(s[1:4]) # 输出: yth (切片从索引1到3)
print(s[:3]) # 输出: Pyt (从开头到索引2)
print(s[3:]) # 输出: hon (从索引3到末尾)
<