跳转至

Python字符串与格式化

概要: Python中的字符串与格式化

创建时间: 2022.10.01 23:55:08

更新时间: 2022.10.02 00:04:24

常量

字面常量

一个字面常量(Literal Constants)的例子是诸如 51.23 这样的数字,或者是如 这是一串文本This is a string 这样的文本。

数字

数字主要分为两种类型——整数(Integers)与浮点数(Floats)。

警告

Python没有单独的long类型。 int类型可以指任何大小的整数。

字符串

一串字符串(String)是 字符(Characters) 的 序列(Sequence)。

单引号、双引号、三引号

  1. 单引号用来指定字符串,如 'Quote me on this'
  2. 被双引号包括的字符串和被单引号括起的字符串其工作机制完全相同。如"What's your name?"
  3. 可以通过使用三个引号—— """ 或 ''' 来指定多行字符串。如:
    Python
    1
    2
    3
    4
    5
    6
    '''
    这是一段多行字符串。这是它的第一行。
    This is the second line.
    "What's your name?," I asked.
    He said "Bond, James Bond."
    '''
    

字符串是不可变的

警告

Python中没有单独的char数据类型。

Python的格式化方法

Python
1
2
3
4
5
age = 20
name = 'Swaroop'

print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
输出如下
Python
Swaroop was 20 years old when he wrote this book
Why is Swaroop playing with that python?

一个字符串可以使用某些特定的格式(Specification),随后, format 方法将被调用,使用这一方法中与之相应的参数替换这些格式。

提示

Python 从 0 开始计数,这意味着索引中的第一位是 0,第二位是1,以此类推。

python中format的更多使用方法

Python
1
2
3
4
5
6
7
# 对于浮点数 '0.333' 保留小数点(.)后三位
print('{0:.3f}'.format(1.0/3))
# 使用下划线填充文本,并保持文字处于中间位置
# 使用 (^) 定义 '___hello___'字符串长度为 11
print('{0:_^11}'.format('hello'))
# 基于关键词输出 'Swaroop wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))
输出如下
Python
1
2
3
333
___hello___
Swaroop wrote A Byte of Python
format中,end的使用方法如下
Python
1
2
3
4
5
6
7
# 通过 end 指定其应以空白结尾:
print('a', end='') #引号内一个空格
print('b', end='')
# 通过 end 指定以空格结尾:
print('a', end=' ') #引号内两个空格
print('b', end=' ')
print('c')
输出为
Python
ab
a b c