Python中处理字符串的方法

Python之所以会成为Web开发的流行语言之一,很重要的一点就是它对于字符串处理的优势。

目前Python有三种格式化处理字符串方法。

1.fstring方法,这种方法是python3.6版本更新一种方法,最为快速也最为方便!看一下是怎么使用的:

f-Strings 使用方法

>>> name = 'hoxis'
>>> age = 18
>>> f"hi, {name}, are you {age}"
'hi, hoxis, are you 18'
>>> F"hi, {name}, are you {age}"
'hi, hoxis, are you 18'
是不是很简洁?!还有更牛叉的!

因为 f-strings 是在运行时计算的,那么这就意味着你可以在其中放置任意合法的 Python 表达式,比如:

运算表达式
>>> f"{ 2 * 3 + 1}"
'7'
调用函数
还可以调用函数:

>>> def test(input):
...     return input.lower()
...
>>> name = "Hoxis"
>>> f"{test(name)} is handsome."
'hoxis is handsome.'
也可以直接调用内置函数:

>>> f"{name.lower()} is handsome."
'hoxis is handsome.'
在类中使用
>>> class Person:
...     def __init__(self,name,age):
...         self.name = name
...         self.age = age
...     def __str__(self):
...         return f"{self.name} is {self.age}"
...     def __repr__(self):
...         return f"{self.name} is {self.age}. HAHA!"
...
>>> hoxis = Person("hoxis",18)
>>> f"{hoxis}"
'hoxis is 18'
>>> f"{hoxis!r}"
'hoxis is 18. HAHA!'
>>> print(hoxis)
hoxis is 18
>>> hoxis
hoxis is 18. HAHA!
多行 f-string
>>> name = 'hoxis'
>>> age = 18
>>> status = 'Python'
>>> message = {
...     f'hi {name}.'
...     f'you are {age}.'
...     f'you are learning {status}.'
... }
>>>
>>> message
{'hi hoxis.you are 18.you are learning Python.'}
这里需要注意,每行都要加上 f 前缀,否则格式化会不起作用:

>>> message = {
...     f'hi {name}.'
...     'you are learning {status}.'
... }
>>> message
{'hi hoxis.you are learning {status}.'}

2.str.format(),这种是我最开始学习的方法,看一下它是如何使用的:

#通过位置
print '{0},{1}'.format('chuhao',20)

print '{},{}'.format('chuhao',20)

print '{1},{0},{1}'.format('chuhao',20)

#通过关键字参数
print '{name},{age}'.format(age=18,name='chuhao')

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __str__(self):
        return 'This guy is {self.name},is {self.age} old'.format(self=self)

print str(Person('chuhao',18))

#通过映射 list
a_list = ['chuhao',20,'china']
print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
#my name is chuhao,from china,age is 20

#通过映射 dict
b_dict = {'name':'chuhao','age':20,'province':'shanxi'}
print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
#my name is chuhao, age is 20,from shanxi

#填充与对齐
print '{:>8}'.format('189')
#     189
print '{:0>8}'.format('189')
#00000189
print '{:a>8}'.format('189')
#aaaaa189

#精度与类型f
#保留两位小数
print '{:.2f}'.format(321.33345)
#321.33

#用来做金额的千位分隔符
print '{:,}'.format(1234567890)
#1,234,567,890

#其他类型 主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。

print '{:b}'.format(18) #二进制 10010
print '{:d}'.format(18) #十进制 18
print '{:o}'.format(18) #八进制 22
print '{:x}'.format(18) #十六进制12

3..str%()方法,这种方法速度较快但是不够清晰明了而且繁琐,是早期PYthon2.X版本的方法,我几乎没用过...但是要保证能看懂,因为很多文档里还是有这种方法的。
例子如下:

1.最方便的


print 'hello %s and %s' % ('df', 'another df')
但是,有时候,我们有很多的参数要进行格式化,这个时候,一个一个一一对应就有点麻烦了,于是就有了第二种,字典形式的。上面那种是tuple形式的。

2.最好用的

print 'hello %(first)s and %(second)s' % {'first': 'df', 'second': 'another df'}


这种字典形式的字符串格式化方法,有一个最大的好处就是,字典这个东西可以和json文件相互转换,所以,当配置文件使用字符串设置的时候,就显得相当方便。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 最先接触编程的知识是在大学里面,大学里面学了一些基础的知识,c语言,java语言,单片机的汇编语言等;大学毕...
    oceanfive阅读 3,151评论 0 7
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,239评论 4 16
  • 人们说,一个转身,永世分离。这句话决绝中总有一点感伤的味道。这个世界很大很美,...
    冰夫阅读 143评论 0 0
  • 离开朗木寺的那天,出发去拉卜楞寺,途径桑科草原。再一次见到高原上的云朵,如此洁白无瑕,令人心醉。我向来是偏爱云...
    十年灯阅读 538评论 0 3