Python 字符串操作全解析:创建、提取与拼接
1. 字符串的创建
在 Python 中,创建字符串最常见的方式是使用引号将文本括起来。单引号、双引号和三引号都能创建字符串对象,且单引号和双引号在创建字符串时可以互换使用,这与 Unix 外壳和 Perl 中的引号使用方式不同。
以下是不同引号创建字符串的示例代码:
string1 = 'This is a string'
string2 = "This is another string"
string3 = '''This is still another string'''
string4 = """And one more string"""
print(type(string1), type(string2), type(string3), type(string4))
输出结果为:
(<type 'str'>, <type 'str'>, <type 'str'>, <type 'str'>)
在 Python 里,如果你需要在字符串中嵌入引号,可以根据引号类型选择合适的引号来避免转义字符的使用。示例如下:
s = "This is a string with 'quotes' in it"
print(s)
s = 'This is a string with \'quotes\' in it'
print(s)
s
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



