python字符串与文本处理技巧(3):字符剔除、字符对齐、字符拼接、字符插入变量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shenziheng1/article/details/83445936

1. 删除字符串中不需要的字符

去掉文本字符串开头,结尾或者中间不想要的字符,比如空白。

  • strip() & Istrip() & rstrip()

strip() 方法能用于删除开始或结尾的字符。 lstrip() rstrip() 分别从左和从右执行删除操作。 默认情况下,这些方法会去除空白字符,也可以指定其他字符。

s = ' hello world \n'
print(s.strip())
# >>> hello world
print(s.lstrip())
# >>> hello world \n
print(s.rstrip())
# >>>   hello world
ss = '-----hello====='
print(ss.strip('-')) 
# >>> hello=====
print(ss.strip('='))
# >>> -----hello
print(ss.strip('-='))
# >>> hello
  • replace() & re.sub()

这些 strip() 方法在读取和清理数据以备后续处理的时候是经常会被用到的。默认情况下strip()方法仅对字符串开头的空格有用。 这种去除操作不会对字符串的中间的文本(指的是空格)产生任何影响。如果为我们想处理字符串中间的空格,那么需要求助其他技术。比如使用replace()方法或者是用正则表达式替换。示例如下:比如:

import re

s = ' hello    world \n'
print(s.strip())
# >>> hello    world 
print(s.replace(' ',''))
# >>> helloworld
print(re.sub('\s+', ' ', s))
# >>>  hello world 

2. 字符串对齐

  • ljust() & rjust() & center()

对于基本的字符串对齐操作,可以使用字符串的 ljust() , rjust() 和 center() 方法。

s = 'hello world'
print(s.ljust(20))
# >>> 'hello world         '
print(s.rjust(20))
# >>> '         hello world'
print(s.center(20))
# >>> '    hello world     '

print(s.ljust(20,'*'))
# >>> hello world*********
print(s.rjust(20,'*'))
# >>> *********hello world
print(s.center(20,'*'))
# >>> ****hello world*****
  • format()
s = 'hello world'
print(format(s, '*>20s'))
# >>> hello world*********
print(format(s, '*<20s'))
# >>> *********hello world
print(format(s, '*^20s'))
# >>> ****hello world*****

format() 函数的一个好处是它不仅适用于字符串。还可以用来格式化任何值。 比如,用它来格式化数字:

x = 3.1415926
print(format(x, '*>10'))
# >>> *3.1415926
print(format(x, '*>10.2f'))
# >>> ******3.14

3. 字符串拼接

将几个小型字符串拼接成一个较大的字符串。

  • join()
parts = ['Are', 'you', 'like', 'China', '?']
print(''.join(parts))
# >>> AreyoulikeChina?
print(' '.join(parts))
# >>> Are you like China ?
print(','.join(parts))
# >>> Are,you,like,China,?

这种语法看上去会比较怪,但是join()被指定为字符串的一个方法。 这样做的部分原因是想去连接的对象可能来自各种不同的数据序列(比如列表,元组,字典,文件,集合或生成器等), 如果在所有这些对象上都定义一个join()方法明显是冗余的。

如果仅仅只是合并少数几个字符串,使用加号(+)通常已经足够了:

4. 字符串中插入变量

很多时候我们需要创建一个内嵌变量的字符串,变量被它的值所表示的字符串替换掉。

  • format()

Python并没有对在字符串中简单替换变量值提供直接的支持。 但是通过使用字符串的format()方法来解决这个问题。比如:

  • format_map() & vars() /// 变量域

或者,如果要被替换的变量能在变量域中找到, 那么我们可以结合使用format_map()  vars() 。例如:

s = '{appName} has {n} messages'
appName = 'QQ'
n = 50
s__ = s.format_map(vars())
print(s__)
# >>> QQ has 50 messages

vars()还有一个有意思的特性就是它也适用于对象实例。比如:

s = '{name} has {n} messages'
class Info:
    def __init__(self, name, n):
        self.name = name
        self.n = n
        
a = Info('Wesee', 50)
print(s.format_map(vars(a)))
# >>> Wesee has 50 messages

Comment : format 和 format_map() 的一个缺陷就是它们并不能很好的处理变量缺失的情况,比如:

s.format(name='Wesee')
>>> Traceback (most recent call last):  File "<stdin>", line 1, in <module>
    KeyError: 'n'

本博文参考《python3-codebook》

猜你喜欢

转载自blog.csdn.net/shenziheng1/article/details/83445936
今日推荐