Python字符串

2019-06-12  本文已影响0人  慕慕她爸

什么是字符串呢?
字符串是有独立的字符组成的一个序列。

字符串基本操作

python当中,单引号、双引号以及三引号的字符串是一模一样的,没有区别。

>>> name = 'jason'
>>> city = 'beijing'
>>> text = 'welcome to jike shijian'
>>> 
>>> s1 = 'hello'
>>> s2 = "hello"
>>> s3 = """hello"""
>>> s1 == s2 == s3
True

特别需要说明的是python的三引号字符串主要用于多行字符串情景,诸如函数的注释等,可以参考下面的例子

def calculate_similarity(item1, item2):
    """
    Calculate similarity between two items
    Args:
        item1: 1st item
        item2: 2nd item
    Returns:
      similarity score between item1 and item2
    """

同时python也支持转义字符串,常见的转义字符见下表

转义字符 说明
\newline 接下一行
\\ 接下一行
\' 表示单引号'
\" 表示双引号"
\n 换行
\t 横向制表符
\b 退格
\v 纵向制表符

简单示列如下所示

>>> s = 'a\nb\tc'
>>> print(s)
a
b   c

>>> len(s)
5

字符串常用操作

字符串支持索引、切片和遍历等操作

>>> name = 'jason'
>>> name[0]
'j'
>>> name[1:3]
'as'

>>> for char in name:
...     print(char)
... 
j
a
s
o
n

需要特别注意的是字符串是不可变的,改变字符串内部字符会出现报错

>>> s = 'hello'
>>> s[0] = 'H'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

如果想把上面示列的'hello'第一个字符'h',改写成'H',推荐下面两种做法

>>> s = 'H' + s[1:]
>>> s = s.replace('h', 'H')

对于字符串拼接,我们推荐+和join操作,示列如下

>>> str1 = 'a'
>>> str2 = 'b'
>>> str1 += str2
>>> str1
'ab'
>>> str2
'b'

使用join 函数按照指定的格式拼接起来
>>> l = []
>>> for n in range(0, 100000):
...     l.append(str(n))
... 
>>> l = ''.join(l)
>>>

对于字符串的分割,我们推荐split函数,示列如下

def query_data(namespace, table):
    """
    given namespace and table, query database to get corressponding
    data
    """
path = 'hive://ads/training_table'
namespace = path.split('//')[1].split('/')[0]
table = path.split('//')[1].split('/')[1]
data = query_data(namespace, table)

其他常见的字符串分割函数还有

string.strip(str) #去掉首尾的str字符串
string.lstrip(str) #去掉开头的str字符串
string.rstrip(str) #去掉尾部的str字符串

字符串的格式化

什么是字符串的格式化呢?一般情况下,我们使用一个字符串作为模板,模板中会有格式符。这些格式符回味后续真实值预留位置,方便真实值呈现应该呈现的格式。通常用在程序的输出、日志打印等场景。
常用的字符串格式化有下面两种方式

>>> id = 123
>>> name = 'jason'
>>> print('no data avaiable for person with id: {}, name: {}'.format(id, name))
no data avaiable for person with id: 123, name: jason

>>> print('no data avaiable for person with id: %s, name: %s' %(id, name))
no data avaiable for person with id: 123, name: jason

format格式是最新的字符串格式化方法,在写程序时优先推荐使用,它同时也是官方推荐的规范。

上一篇下一篇

猜你喜欢

热点阅读