码农行者 码农行者
首页
  • Python

    • 语言特性
    • Django相关
    • Tornado
    • Celery
  • Golang

    • golang学习笔记
    • 对比python学习go
    • 模块学习
  • JavaScript

    • Javascript
  • 数据结构预算法笔记
  • ATS
  • Mongodb
  • Git
云原生
运维
垃圾佬的快乐
  • 数据库
  • 机器学习
  • 杂谈
  • 面试
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

DeanWu

软件工程师
首页
  • Python

    • 语言特性
    • Django相关
    • Tornado
    • Celery
  • Golang

    • golang学习笔记
    • 对比python学习go
    • 模块学习
  • JavaScript

    • Javascript
  • 数据结构预算法笔记
  • ATS
  • Mongodb
  • Git
云原生
运维
垃圾佬的快乐
  • 数据库
  • 机器学习
  • 杂谈
  • 面试
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 「Python Tips」- 40中常用Python string用法

    • 1/ 创建字符串
      • 2/ 使用 print 语句查看输出
        • 3/ 单行查看输出
          • 4/ 单行 \n 查看输出
            • 5/ 字符串下标表示法
              • 6/ 下标字符串相加
                • 7/ 切片字符串
                  • 8/ 负索引切片
                    • 9/ %格式化操作符
                      • 10/ 带整数的%
                        • 11/ %用于站位
                          • 12/ 利用 \n 分拆字符串
                            • 13/ 多个\n
                              • 14/ 其他方式使用%
                                • 15/ 字串符转为整数
                                  • 16/ 获取单个字符在字符串中出现的次数
                                    • 17/ 将字符串变为大写
                                      • 18/ 将字符串变为小写
                                        • 19/ 组合字符串
                                          • 20/ 分拆字符串
                                            • 21/ 判断字符串是否是大写
                                              • 22/ 判断字符串是否是小写
                                                • 23/ 判断字符串是否有字母数字构成
                                                  • 24/ 获取字符串的长度
                                                    • 25/ 将字符串转化为 10 进制的 asscii 码
                                                      • 26/ 将 10 进制的 asscii 码转化为字符串
                                                        • 27/ 转义字符
                                                          • 28/ 使用逗号格式化字符串
                                                            • 29/ format 格式化字符串
                                                              • 30/ format 中通过名字传递字符
                                                                • 31/ format 中通过参数顺序传递字符
                                                                  • 32/ format 中访问对象属性
                                                                    • 33/ 对齐文本
                                                                      • 34/ 格式化二进制、八进制和十六进制
                                                                        • 35/ 使用逗号作为分隔符
                                                                          • 36/ 使用f来格式化字符串
                                                                            • 37/ 使用模板格式化字符串
                                                                              • 38/ 字符串的遍历
                                                                                • 39/ 使用 while 循环
                                                                                  • 40/ 使用三引号保存字符串
                                                                                    • 参考:
                                                                                    • 开发语言
                                                                                    • Python
                                                                                    • 语言特性
                                                                                    DeanWu
                                                                                    2020-10-21
                                                                                    目录

                                                                                    「Python Tips」- 40中常用Python string用法

                                                                                    文章首发公众号:CoderMrWu ,每周分享优质技术文章和经验,欢迎大家关注,共同交流。

                                                                                    今天看了篇文章总结了 40 种Python String 类型的常用语法,觉着很有趣,翻译重新整理分享给大家。尽管有些语法你可能用不到,但也算是掌握一种奇思巧技。

                                                                                    # 1/ 创建字符串

                                                                                    s1 = 'This is a test.'
                                                                                    
                                                                                    1

                                                                                    # 2/ 使用 print 语句查看输出

                                                                                    # python3/python2
                                                                                    >>> print('this is a test.')
                                                                                    this is a test.
                                                                                    # python3/python2
                                                                                    >>> print ('test')
                                                                                    test
                                                                                    # python2
                                                                                    >>> print '123'
                                                                                    123
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9

                                                                                    # 3/ 单行查看输出

                                                                                    >>> s1 = 'this is'
                                                                                    >>> s2 = ' a test'
                                                                                    >>> print(s1+s2)
                                                                                    this is a test
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4

                                                                                    # 4/ 单行 \n 查看输出

                                                                                    >>> print(s1+'\n'+s2)
                                                                                    this is
                                                                                     a test
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3

                                                                                    # 5/ 字符串下标表示法

                                                                                    >>> print(s1[0])
                                                                                    t
                                                                                    >>> print(s1[1])
                                                                                    h
                                                                                    >>> print(s1[8])
                                                                                    Traceback (most recent call last):
                                                                                      File "<input>", line 1, in <module>
                                                                                    IndexError: string index out of range
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8

                                                                                    # 6/ 下标字符串相加

                                                                                    >>> print(s1[1]+s1[3]+s1[4])
                                                                                    hs
                                                                                    
                                                                                    1
                                                                                    2

                                                                                    # 7/ 切片字符串

                                                                                    >>> print(s1[0:5])
                                                                                    this
                                                                                    >>> print(s1[0:])
                                                                                    this is
                                                                                    >>> print(s1[:])
                                                                                    this is
                                                                                    >>> print(s1[:-1])
                                                                                    this i
                                                                                    >>> print(s1[::2])
                                                                                    ti s
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10

                                                                                    # 8/ 负索引切片

                                                                                    >>> print(s1[-5:-1])
                                                                                    is i
                                                                                    >>> print(s1[-1::-1])  # 反转字符串
                                                                                    si siht
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4

                                                                                    # 9/ %格式化操作符

                                                                                    >>> print('this is a %s' % 'test')
                                                                                    this is a test
                                                                                    >>> print('this is a %(test)s' % {'test':'12345'})
                                                                                    this is a 12345
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4

                                                                                    # 10/ 带整数的%

                                                                                    >>> print('1+1 = %(num)01d' % {'num': 2})
                                                                                    1+1 = 2
                                                                                    >>> print('1+1 = %(num)02d' % {'num': 2})
                                                                                    1+1 = 02
                                                                                    >>> print('1+1 = %(num)03d' % {'num': 2})
                                                                                    1+1 = 002
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6

                                                                                    # 11/ %用于站位

                                                                                    >>> print( '%(a)s %(n)03d - program is the best.' % {'a':'Python','n':3})
                                                                                    Python 003 - program is the best.
                                                                                    
                                                                                    1
                                                                                    2

                                                                                    # 12/ 利用 \n 分拆字符串

                                                                                    >>> print(' %(a)s %(n)03d - program is the best \n %(a)s helped me understand programming.' % {"a":"Python","n":3})
                                                                                    Python 003 - program is the best
                                                                                    Python helped me understand programming.
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3

                                                                                    # 13/ 多个\n

                                                                                    >>> print(' I love %(a)s. \n I like %(b)s. \n I like to %(c)s. \n my %(d)s is %(num)03d.'%{"a":"to code","b":"ice-cream","c":"travel","d":"age","num":32})
                                                                                    I love to code.
                                                                                    I like ice-cream.
                                                                                    I like to travel.
                                                                                    my age is 032.
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5

                                                                                    # 14/ 其他方式使用%

                                                                                    >>> print('Hello everyone I am using Python %d.7 version.' % 3.7)
                                                                                    Hello everyone I am using Python 3.7 version.
                                                                                    
                                                                                    >>> print('%s %s %d %d %f %f' % ('Hercules', 'Zeus', 100, 20, 3.2, 1))
                                                                                    Hercules Zeus 100 20 3.200000 1.000000
                                                                                    
                                                                                    >>> print('This is a +%d integer' % 10)
                                                                                    This is a +10 integer
                                                                                    
                                                                                    >>> print('This is a negative -%d integer' % 250)
                                                                                    This is a negative -250 integer
                                                                                    
                                                                                    >>> print('This is a confused -%d integer' % 300)
                                                                                    This is a confused -300 integer
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10
                                                                                    11
                                                                                    12
                                                                                    13
                                                                                    14

                                                                                    # 15/ 字串符转为整数

                                                                                    >>> s3 = '123'
                                                                                    >>> print(10*int(s3))  # 乘法
                                                                                    1230
                                                                                    >>> print(10*s3)  # 倍数
                                                                                    123123123123123123123123123123
                                                                                    >>> print('1'+'45')
                                                                                    145
                                                                                    
                                                                                    >>> print('1'+45)
                                                                                    Traceback (most recent call last):
                                                                                      File "<stdin>", line 1, in <module>
                                                                                    TypeError: can only concatenate str (not "int") to str
                                                                                    
                                                                                    
                                                                                    >>> print(float('1')+float('45'))
                                                                                    46.0
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10
                                                                                    11
                                                                                    12
                                                                                    13
                                                                                    14
                                                                                    15
                                                                                    16

                                                                                    # 16/ 获取单个字符在字符串中出现的次数

                                                                                    >>> text = 'this is a test.'
                                                                                    >>> print(text.count('t'))
                                                                                    3
                                                                                    >>> print(text.count('is'))
                                                                                    2
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5

                                                                                    # 17/ 将字符串变为大写

                                                                                    >>> text = 'this is a test.'
                                                                                    >>> print(text.upper())
                                                                                    THIS IS A TEST.
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4

                                                                                    # 18/ 将字符串变为小写

                                                                                    >>> text = 'THIS IS A TEST.'
                                                                                    >>> print(text.upper())
                                                                                    this is a test.
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3

                                                                                    # 19/ 组合字符串

                                                                                    >>> ' '.join(text)
                                                                                    't h i s   i s   a   t e s t .'
                                                                                    
                                                                                    >>> ','.join(['hello', 'Dean'])
                                                                                    'hello,Dean'
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6

                                                                                    # 20/ 分拆字符串

                                                                                    >>> text = 'this is a test.'
                                                                                    >>> print(text.split(' '))
                                                                                    ['this', 'is', 'a', 'test.']
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4

                                                                                    # 21/ 判断字符串是否是大写

                                                                                    >>> text
                                                                                    'this is a test.'
                                                                                    >>> up_text = text.upper()
                                                                                    >>> print(up_text.isupper())
                                                                                    True
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5

                                                                                    # 22/ 判断字符串是否是小写

                                                                                    >>> low_text = text.lower()
                                                                                    >>> print(low_text.islower())
                                                                                    True
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4

                                                                                    # 23/ 判断字符串是否有字母数字构成

                                                                                    >>> text1 = 'Lession 01'
                                                                                    >>> print(text1.isalnum())
                                                                                    False
                                                                                    >>> text2 = 'Lession01'
                                                                                    >>> print(text2.isalnum())
                                                                                    True
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6

                                                                                    # 24/ 获取字符串的长度

                                                                                    >>> text
                                                                                    'this is a test.'
                                                                                    >>> print(len(text))
                                                                                    15
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5

                                                                                    # 25/ 将字符串转化为 10 进制的 asscii 码

                                                                                    >>> print(ord('A'))
                                                                                    65
                                                                                    >>> print(ord('B'))
                                                                                    66
                                                                                    >>> print(ord('a'))
                                                                                    97
                                                                                    >>> print(ord('b'))
                                                                                    98
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8

                                                                                    # 26/ 将 10 进制的 asscii 码转化为字符串

                                                                                    >>> print(chr(65))
                                                                                    A
                                                                                    >>> print(chr(42))
                                                                                    *
                                                                                    >>> print(chr(118))
                                                                                    v
                                                                                    >>> print(chr(60))
                                                                                    <
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8

                                                                                    # 27/ 转义字符

                                                                                    >>> print('What\'s up?')
                                                                                    What's up?
                                                                                    
                                                                                    >>> # the apostrophe is not needed in this case.
                                                                                    >>> print("What's up?")
                                                                                    What's up?
                                                                                    
                                                                                    >>> # the apostrophe is needed to add on the quotes to the text
                                                                                    >>> print("\"What's up?\"")
                                                                                    "What's up?"
                                                                                    
                                                                                    >>> # triple quotes can escape single, double, and a lot more.
                                                                                    >>> print("""What's up? Does the "" need an escape?""")
                                                                                    What's up? Does the "" need an escape?
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10
                                                                                    11
                                                                                    12
                                                                                    13
                                                                                    14

                                                                                    # 28/ 使用逗号格式化字符串

                                                                                    >>> print('这里有', 10, '个苹果')
                                                                                    这里有 10 个苹果
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3

                                                                                    # 29/ format 格式化字符串

                                                                                    >>> text
                                                                                    'this is a test.'
                                                                                    >>> print('This is a {}'.format(text))
                                                                                    This is a this is a test.
                                                                                    >>> print('Number {1} and number {0}'.format(100, 200))  # keyword position
                                                                                    Number 200 and number 100
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6

                                                                                    # 30/ format 中通过名字传递字符

                                                                                    >>> print('这里有{num}个{type}。'.format(num=10, type='苹果'))
                                                                                    这里有10个苹果。
                                                                                    >>> tmp = {'num': 10, 'type': '苹果'}
                                                                                    >>> print('这里有{num}个{type}。'.format(**tmp))
                                                                                    这里有10个苹果。
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6

                                                                                    # 31/ format 中通过参数顺序传递字符

                                                                                    >>> print('这里有{1}个{0}。'.format('苹果',10))
                                                                                    这里有10个苹果。
                                                                                    
                                                                                    1
                                                                                    2

                                                                                    # 32/ format 中访问对象属性

                                                                                    >>> class Rectangle:
                                                                                     def __init__(self, length, width):
                                                                                      self.length = length
                                                                                      self.width = width
                                                                                     def __str__(self):
                                                                                      return 'Rectangle({self.length}, {self.width})'.format(self=self)
                                                                                    
                                                                                    
                                                                                    >>> rect = Rectangle(10, 5.5)
                                                                                    >>> print(rect.__str__())
                                                                                    Rectangle(10, 5.5)
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10
                                                                                    11

                                                                                    # 33/ 对齐文本

                                                                                    >>> print('{:<10}'.format('X')) # left align
                                                                                    X
                                                                                    >>> print('{:>10}'.format('X')) # right align
                                                                                             X
                                                                                    >>> print('{:^10}'.format('X')) # center
                                                                                        X
                                                                                    >>> print('{:?^10}'.format('X')) # add a fill character
                                                                                    ????X?????
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8

                                                                                    # 34/ 格式化二进制、八进制和十六进制

                                                                                    >>> print('Binary number: {0:b}'.format(50))
                                                                                    Binary number: 110010
                                                                                    
                                                                                    >>> print('Octal number: {0:o}'.format(100))
                                                                                    Octal number: 144
                                                                                    
                                                                                    >>> print('Hexadecimal number: {0:x}'.format(2555))
                                                                                    Hexadecimal number: 9fb
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8

                                                                                    # 35/ 使用逗号作为分隔符

                                                                                    >>> print('{:,}'.format(2783727282727))
                                                                                    2,783,727,282,727
                                                                                    
                                                                                    >>> print('{:.2%}'.format(90.60/100))
                                                                                    90.60%
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5

                                                                                    # 36/ 使用f来格式化字符串

                                                                                    >>> item_1, item_2, item_3 = 'computer', 'mouse', 'browser'
                                                                                    
                                                                                    >>> print(f"He uses a {item_1}.")
                                                                                    He uses a computer.
                                                                                    
                                                                                    >>> print(f"He uses a {item_2} and a {item_3}.")
                                                                                    He uses a mouse and a browser.
                                                                                    
                                                                                    >>> print(f"He uses a {item_1} 3 times a day.")
                                                                                    He uses a computer 3 times a day.
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10

                                                                                    # 37/ 使用模板格式化字符串

                                                                                    # docs: https://docs.python.org/3/library/string.html#template-strings
                                                                                    >>> from string import Template
                                                                                    >>> poem = Template('$x are red and $y are blue')
                                                                                    
                                                                                    >>> print(poem.substitute(x='roses', y='violets'))
                                                                                    roses are red and violets are blue
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6

                                                                                    # 38/ 字符串的遍历

                                                                                    >>> text
                                                                                    'this is a test.'
                                                                                    >>> for item in text:
                                                                                    ...     print(item)
                                                                                    ...
                                                                                    t
                                                                                    h
                                                                                    i
                                                                                    s
                                                                                    
                                                                                    i
                                                                                    s
                                                                                    
                                                                                    a
                                                                                    
                                                                                    t
                                                                                    e
                                                                                    s
                                                                                    t
                                                                                    .
                                                                                    
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10
                                                                                    11
                                                                                    12
                                                                                    13
                                                                                    14
                                                                                    15
                                                                                    16
                                                                                    17
                                                                                    18
                                                                                    19
                                                                                    20
                                                                                    21

                                                                                    # 39/ 使用 while 循环

                                                                                    >>> i = 0
                                                                                    >>> while i < len(text):
                                                                                            print(text[i])
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3

                                                                                    # 40/ 使用三引号保存字符串

                                                                                    >>> def triple_quote_docs():
                                                                                     """
                                                                                     In the golden lightning
                                                                                     Of the sunken sun,
                                                                                     O'er which clouds are bright'ning,
                                                                                     Thou dost float and run,
                                                                                     Like an unbodied joy whose race is just begun.
                                                                                     """
                                                                                     return
                                                                                    
                                                                                    >>> print(triple_quote_docs.__doc__)
                                                                                    
                                                                                     In the golden lightning
                                                                                     Of the sunken sun,
                                                                                     O'er which clouds are bright'ning,
                                                                                     Thou dost float and run,
                                                                                     Like an unbodied joy whose race is just begun.
                                                                                    
                                                                                    >>>
                                                                                    
                                                                                    1
                                                                                    2
                                                                                    3
                                                                                    4
                                                                                    5
                                                                                    6
                                                                                    7
                                                                                    8
                                                                                    9
                                                                                    10
                                                                                    11
                                                                                    12
                                                                                    13
                                                                                    14
                                                                                    15
                                                                                    16
                                                                                    17
                                                                                    18
                                                                                    19

                                                                                    # 参考:

                                                                                    • https://pysnakeblog.blogspot.com/2019/09/top-40-python-string-processing-in.html (opens new window)
                                                                                    #Python
                                                                                    上次更新: 2023/03/28, 16:27:19
                                                                                    最近更新
                                                                                    01
                                                                                    chromebox/chromebook 刷bios步骤
                                                                                    03-01
                                                                                    02
                                                                                    redis 集群介绍
                                                                                    11-28
                                                                                    03
                                                                                    go语法题二
                                                                                    10-09
                                                                                    更多文章>
                                                                                    Theme by Vdoing | Copyright © 2015-2024 DeanWu | 遵循CC 4.0 BY-SA版权协议
                                                                                    • 跟随系统
                                                                                    • 浅色模式
                                                                                    • 深色模式
                                                                                    • 阅读模式