基础
可用单引号,双引号,或者三引号:
1
2
3name = 'jason'
city = 'beijing'
text = "welcome to jike shijian"Python 的三引号字符串,则主要应用于多行字符串的情境. e.g. 函数的注释
- 转义字符(反斜杠开头):
- \newline: 接下一行
- \: \
常用操作
支持索引,切片和遍历等等操作
1
2
3
4
5name = 'Jason'
name[0]
'J'
name[1:3]
'as'遍历字符串相当于遍历字符串中的每个字符
for char in name
Python 的字符串是不可变的: 改变一个字符串内部的字符是不允许的。
1
2
3
4
5s = 'hello'
s[0] = 'H'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignmentPython 中字符串的改变,通常只能通过创建新的字符串来完成
1
2s = 'H' + s[1:]
s = s.replace('h', 'H')字符串拼接方法:
使用 ‘+=’ :
1
2
3s = ''
for n in range(0, 100000):
s += str(n)使用内置函数 join :
1
2
3
4l = []
for n in range(0, 100000):
l.append(str(n))
l = ' '.join(l)
字符串分割:
- split(): string.split(separator),表示把字符串按照 separator 分割成子字符串并返回一个分割后子字符串组合的列表
1
2
3
4
5
6
7
8
9
10def query_data(namespace, table):
"""
given namespace and table, query database to get corresponding
data
"""
path = 'hive://ads/training_table'
namespace = path.split('//')[1].split('/')[0] # 返回'ads'
table = path.split('//')[1].split('/')[1] # 返回 'training_table'
data = query_data(namespace, table)
- split(): string.split(separator),表示把字符串按照 separator 分割成子字符串并返回一个分割后子字符串组合的列表
其他函数:
- string.strip(str),表示去掉首尾的 str 字符串
- string.lstrip(str),表示去掉开头的 str 字符串
- string.rstrip(str),表示去掉结尾的 str 字符串
- string.find(sub, start, end),表示从 start 到 end 查找字符串中子字符串 sub 的位置
字符串的格式化
1 | print('no data available for person with id: {}, name: {}'.format(id, name)) |
\newline