1. 使用单引号:
my_string = 'this is a string!'
2. 使用双引号:
my_string = "this is also a string!"
3. 使用三引号(用于多行字符串):
my_string = """this is a
multi-line
string!"""
4. 转义字符:
使用反斜杠 `\` 转义单引号或双引号:
my_string = 'He said, "Hello!"'
5. 字符串拼接:
my_string = 'Hello' + ' ' + 'There'
6. 字符串重复:
my_string = 'hello' * 5
7. 字符串长度:
my_string = 'hello'
print(len(my_string)) 输出:5
8. 字符串切片:
my_string = 'hello world'
print(my_string[0:5]) 输出:hello
9. 字符串去除空白:
my_string = ' hello '
print(my_string.strip()) 输出:'hello'
10. 字符串去除开头或结尾的字符:
my_string = 'hello'
print(my_string.lstrip('')) 输出:'hello'
print(my_string.rstrip('')) 输出:'hello'
以上是Python中创建和处理字符串的基本方法。