Python_字符串技巧总结记录

特殊属性

r/R 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。
print( r'\n' )
print( R'\n' )
% 格式字符串 请看下一节内容。
>>> print( r"I will print \n, then print \\\\r" )
I will print \n, then print \\\\r

格式化字符串

<1> 百分号 %

>>> print( "Major: %s, Number: %d." % ( "计算机科学与技术", 23401 ) )
Major: 计算机科学与技术, Number: 23401.
    符   号 描述
      %c  格式化字符及其ASCII码
      %s  格式化字符串
      %d  格式化整数
      %u  格式化无符号整型
      %o  格式化无符号八进制数
      %x  格式化无符号十六进制数
      %X  格式化无符号十六进制数(大写)
      %f  格式化浮点数字,可指定小数点后的精度
      %e  用科学计数法格式化浮点数
      %E  作用同%e,用科学计数法格式化浮点数
      %g  %f和%e的简写
      %G  %f 和 %E 的简写
      %p  用十六进制数格式化变量的地址
符号 功能
* 定义宽度或者小数点精度
- 用做左对齐
+ 在正数前面显示加号( + )
<sp> 在正数前面显示空格
# 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
0 显示的数字前面填充'0'而不是默认的空格
% '%%'输出一个单一的'%'
(var) 映射变量(字典参数)
m.n. m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

<2> str.format() ( 2.6版本后添加 )

>>> "{:^10s}".format("123")
'   123    '

>>> print("{:.2f}".format(3.1415926));
3.14
数字 格式 输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:>10d}         13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d}     13 中间对齐 (宽度为10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
进制

^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

+ 表示在正数前显示 +,负数前显示 -  (空格)表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

此外我们可以使用大括号 {} 来转义大括号

>>> print ("{} 对应的位置是 {{0}}".format("csdn"))
csdn 对应的位置是 {0}

<3> f-string 表达式 ( 3.6版本后添加 )

>>> name = "张三"
>>> age = 25
>>> print( f"Hi, {name}. Your age is {age}." )
Hi, 张三. Your age is 25.

详细用法待补充

资料一
资料二

<4> 成员方法

居中对齐 center(self, width, fillchar=’ ', /)

Help on method_descriptor:

center(self, width, fillchar=' ', /)
    Return a centered string of length width.

    Padding is done using the specified fill character (default is a space).
>>> string = "python"
>>> string
'python'
>>> string.center(10)
'  python  '
>>> string.center(10,"0")
'00python00'

左对齐 ljust(self, width, fillchar=’ ', /)

Help on method_descriptor:

ljust(self, width, fillchar=' ', /)
    Return a left-justified string of length width.

    Padding is done using the specified fill character (default is a space).
>>> string.ljust(10)
'python    '
>>> string.ljust(10,"0")
'python0000'

右对齐 rjust(self, width, fillchar=’ ', /)

>>> help(str.rjust)
Help on method_descriptor:

rjust(self, width, fillchar=' ', /)
    Return a right-justified string of length width.

    Padding is done using the specified fill character (default is a space).
>>> string.rjust(10,"0")
'0000python'

str.zfill 和 str.rjust 区别

Help on method_descriptor:

zfill(self, width, /)
    Pad a numeric string with zeros on the left, to fill a field of the given width.

    The string is never truncated.
  • zfill : 右对齐, 只能 0 填充
  • rjust : 右对齐, 默认以 空格 填充, 可指定任意符号

所以说, 二者是包含和被包含的关系

清除指定字符 str.strip(self, chars=None, /)

>>> help(str.strip)
Help on method_descriptor:

strip(self, chars=None, /)
    Return a copy of the string with leading and trailing whitespace remove.

    If chars is given and not None, remove characters in chars instead.
>>> help(str.lstrip)
Help on method_descriptor:

lstrip(self, chars=None, /)
    Return a copy of the string with leading whitespace removed.

    If chars is given and not None, remove characters in chars instead.
>>> help(str.rstrip)
Help on method_descriptor:

rstrip(self, chars=None, /)
    Return a copy of the string with trailing whitespace removed.

    If chars is given and not None, remove characters in chars instead.
>>> string1 = " python "
>>> string1.strip()
'python'

>>> string2 = "_python_"
>>> string2.strip("_")
'python'

>>> string3 = "____python____"
>>> string3.lstrip("_")
'python____'
>>> string3.rstrip("_")
'____python'

截取 str.split(self, /, sep=None, maxsplit=-1)

Help on method_descriptor:

split(self, /, sep=None, maxsplit=-1)
    Return a list of the words in the string, using sep as the delimiter string.

    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.

连接 join(self, iterable, /)

Help on method_descriptor:

join(self, iterable, /)
    Concatenate any number of strings.

    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.

    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
>>> myTuple = ( 1, 2, 3 )
>>> "_".join( myTuple )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>> myTuple = ( '1', '2', '3' )
>>> "_".join( myTuple )
'1_2_3'

>>> "".join(myTuple)
'123'
发布了160 篇原创文章 · 获赞 146 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44510468/article/details/104073434