美文网首页
深入浅出字符串

深入浅出字符串

作者: 倔强的潇洒小姐 | 来源:发表于2019-05-25 22:42 被阅读0次

    注:Python 的字符串是不可变的(immutable)

    使用场景:
    日志的打印、程序中函数的注释、数据库的访问、变量的基本操作

    写法:

    • 单引号(''),如 name = 'zhangsan'
    • 双引号(""),如 gender = "male"
    • 三引号之中(''' '''或 """ """):主要应用于多行字符串的情境,比如函数的注释
    def calculate_similarity(item1, item2):
        """
        Calculate similarity between two items
        Args:
            item1: 1st item
            item2: 2nd item
        Returns:
          similarity score between item1 and item2
        """
    



    转义字符:
    用反斜杠开头的字符串,来表示一些特定意义的字符

    转义字符.png

    字符串的拼接方法:

    • 加号:str1 += str2
    • 内置函数 json:
    l = []
    for n in range(0, 100000):
        l.append(str(n))
    l = ' '.join(l)
    print(l)
    

    字符串的分割方法:string.split(separator)
    场景:常常应用于对数据的解析处理,比如我们读取了某个文件的路径,想想要调用数据库的 API,去读取对应的数据

    def 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) 
    



    字符串的去空格方法:

    • 首尾空格:string.strip(str),str表示需要去除空格的字符串
    • 前空格:lstrip
    • 尾空格:rstrip



    字符串的查找方法:
    string.find(sub, start, end):表示从 start 到 end 查找字符串中子字符串 sub的位置



    字符串的格式化:
    场景:通常会用在程序的输出、logging
    比如我们有一个任务,给定一个用户的 userid,要去数据库中查询该用户的一些信息,并返回。而如果数据库中没有此人的信息,我们通常会记录下来,这样有利于往后的日志分析,或者是线上bug 的调试

    • string.format()
      注:大括号{}就是所谓的格式符,用来为后面的真实值——变量 name 预留位置。
    id = '123'
    name='zhangsan'
    print('no data available for person with id:{}, name:{}'.format(id, name))
    
    • f-string(Python3.6引入):以 f 或 F 修饰符引领的字符串(f'xxx' 或 F'xxx'),以大括号 {} 标明被替换的字段;在本质上并不是字符串常量,而是一个在运行时运算求值的表达式
      官方解释:While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
    print(f'no data available for person with id:{id}, name:{name}')
    



    思考题:
    下面的两个字符串拼接操作,你觉得哪个更优呢?
    A:

    s = ''
    for n in range(0, 1000000):
        s += str(n)
    

    B:

    l = []
    for n in range(0, 1000000):
        l.append(str(n))
        
    s = ' '.join(l)
    

    C:

    s = ''.join(map(str, range(0, 1000000)))
    

    D:

    s = ''.join([str[i] for i in range(0, 1000000)])
    

    代码解答:

    import time
    
    # A
    start_time1 = time.perf_counter()
    s1 = ''
    for n in range(0, 1000000):
        s1 += str(n)
    end_time1 = time.perf_counter()
    print(f'time elapse1: {end_time1 - start_time1}')
    
    # B
    start_time2 =time.perf_counter()
    s2 = []
    for n in range(0, 1000000):
        s2.append(str(n))
    end_time2 = time.perf_counter()
    print(f'time elapse2: {end_time2 - start_time2}')
    
    # C
    start_time3 = time.perf_counter()
    s3 = ''.join(map(str, range(0, 1000000)))
    end_time3 = time.perf_counter()
    print(f'time elapse3: {end_time3 - start_time3}')
    
    # D
    start_time4 = time.perf_counter()
    l = [str(i) for i in range(0, 1000000)]
    s4 = ''.join(l)
    end_time4 = time.perf_counter()
    print(f'time elapse4: {end_time4 - start_time4}')
    

    输出时间:

    time elapse1: 2.5405207
    time elapse2: 0.38024557800000025
    time elapse3: 0.256282659
    time elapse4: 0.28742126300000015
    

    补充说明:数据越大,方案C越高效,效果更明显
    由此可见,join map 具有最好的性能,列表生成器 + join 次之, append + join慢一些,+=最慢

    相关文章

      网友评论

          本文标题:深入浅出字符串

          本文链接:https://www.haomeiwen.com/subject/yktttctx.html