字符串格式化

字符串格式化使用字符串格式化操作符%来实现:格式化字符串 % 值(字符串或者数字或者多个值的元组,字典)

>>> format = "hello, %s. %s are a good gril"
>>> values = ('zyj' ,'you')
>>> print(format % values)
hello, zyj. you are a good gril
>>>

若字符串中包含%,则需要%%进行处理

>>> format1 = 'percent:%.2f%%'
>>> values = 10.123
>>> print(format1 % values)
percent:10.12%
>>>   

可选参数:
参数1:转换标志:- 表示左对齐,默认为右对齐; + 表示在转换之前加上正负号; ''空白字符表示正数之前保留空格;0表示转换值若位数不够用0填充
参数2:最小字段宽度:转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度会从元组中提取
参数3:.后跟精度值:若为实数,精度值表示出现在小数点后的位数,若为字符串,那么该数字表示最大字段宽度。若是*精度将从元组中读出

>>> print('%x' % 16)
10
>>> print('%o' % 8)
10
>>> print('%s' % 'hello')
hello
>>> print('%r' % '42L')
'42L'
>>> from math import pi
>>> print('%10f' % pi)
3.141593
>>> print('%10.2f' % pi)
3.14
>>> print('%.2f' % pi)
3.14
>>> print('%10.5s' % 'hello,world')
hello
>>> format = '%*.*s'
>>> values = 'hello,world'
>>> print(format % (10,5,values))
hello
>>> print('%010.2f' % pi)
0000003.14
>>> print('%-10.2f' % pi)
3.14
>>> print(('% 5d' % 10) + '\n' +('% 5d' % -10))
10
-10
>>> print(('%+5d' % 10) + '\n' +('%+5d' % -10))
+10
-10
>>>

举例:在屏幕上打印九九乘法表:

print("九九乘法表:")
for x in range(1, 10):
for y in range(1, x + 1):
format1 = "%2d%s%-d%s%2d"
tuple1 = (x, ' * ', y, ' = ', x * y)
print(format1 % tuple1, end='')
print(" " * 4, end='')
print("\n") >>>
九九乘法表:
1 * 1 = 1 2 * 1 = 2 2 * 2 = 4 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 >>>

字符串方法

find :在较长的字符串中查找子串。返回子串所在位置的最左端索引。如果没有找到返回-1
此方法可以接收可选的起始点和结束点参数;注意:包含第一个索引,但不包含第二个索引

>>> subject = "hello,world"
>>> print(subject.find('world',2))
6
>>>

join:用来连接序列中的元素,需要被连接的序列元素都必须是字符串。

>>> dirs ='','usr','bin','env'
>>> print('/'.join(dirs))
/usr/bin/env
>>> print('\\'.join(dirs))
\usr\bin\env
>>> ipAddr = ['12','1','1','1']
>>> netMask = ['255','255','255','0']
>>> print('.'.join(ipAddr)+' '+'.'.join(netMask))
12.1.1.1 255.255.255.0
>>>

split:将字符串分割成序列,方法中可以不提供分隔符。程序会把所有的空格作为分隔符

>>> print("I love you".split())
['I', 'love', 'you']
>>> print(list("I love you"))
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u']
>>> print(tuple("I love you"))
('I', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u')
>>> print('1+2-3+5'.split('+'))
['1', '2-3', '5']
>>>

lower:返回字符串的小写字母,在‘不区分大小写’的时候,进行存储和查找。

>>> print(string1.lower())
hello,world
>>> print('hello' in string1.lower())
True
>>>

title:字符串中的所有字母的首字母大写。

>>> title1 = 'jave script'
>>> print(title1.title())
Jave Script
>>>

string模块的capwords函数

>>> import string
>>> print(string.capwords("jave script"))
Jave Script
>>>

replace:返回某字符串的所有匹配项均被替换之后得到的字符串

>>> string2 = 'this is a test'
>>> print(string2.title().replace('is','at'))
That Is A Test
>>> print(string2)
this is a test
>>>

strip:返回去除字符串两侧空格,可以增加参数以去掉特定的字符

>>> string3 = ' show memory -more- '
>>> print(string3.strip())
show memory -more-
>>> psws = ['a','b']
>>> psw = 'a '
>>> print(psw in psws)
False
>>> print(psw.strip() in psws)
True
>>> string4 ='####!!!!*****happy birthday to you*****####!!!!'
>>> print(string4.title().strip('#!'))
*****Happy Birthday To You*****
>>> print(string4.title().rstrip('!#'))
####!!!!*****Happy Birthday To You*****
>>> print(string4.title().lstrip('!#'))
*****Happy Birthday To You*****####!!!!
>>> string5 ='####!!!!###!!!####!!!!'
>>> print(string5.strip('#!')) >>>

translate:替换字符串中的某些部分,只能处理单个字符;如替换因平台而异的特殊字符。

python字符串的更多相关文章

  1. 关于python字符串连接的操作

    python字符串连接的N种方式 注:本文转自http://www.cnblogs.com/dream397/p/3925436.html 这是一篇不错的文章 故转 python中有很多字符串连接方式 ...

  2. StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing the strings?

    StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing t ...

  3. Python 字符串

    Python访问字符串中的值 Python不支持单字符类型,单字符也在Python也是作为一个字符串使用. Python访问子字符串,可以使用方括号来截取字符串,如下实例: #!/usr/bin/py ...

  4. python字符串方法的简单使用

    学习python字符串方法的使用,对书中列举的每种方法都做一个试用,将结果记录,方便以后查询. (1) s.capitalize() ;功能:返回字符串的的副本,并将首字母大写.使用如下: >& ...

  5. python字符串基础知识

    1.python字符串可以用"aaa",'aaa',"""aaa""这三种方式来表示 2.python中的转义字符串为" ...

  6. Python 字符串格式化

    Python 字符串格式化 Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存 一 ...

  7. Python 字符串操作

    Python 字符串操作(string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分割等) 去空格及特殊符号 s.strip() .lstrip() .rstrip(',') 复制字符 ...

  8. 【C++实现python字符串函数库】strip、lstrip、rstrip方法

    [C++实现python字符串函数库]strip.lstrip.rstrip方法 这三个方法用于删除字符串首尾处指定的字符,默认删除空白符(包括'\n', '\r', '\t', ' '). s.st ...

  9. 【C++实现python字符串函数库】二:字符串匹配函数startswith与endswith

    [C++实现python字符串函数库]字符串匹配函数startswith与endswith 这两个函数用于匹配字符串的开头或末尾,判断是否包含另一个字符串,它们返回bool值.startswith() ...

  10. 【C++实现python字符串函数库】一:分割函数:split、rsplit

    [C++实现python字符串函数库]split()与rsplit()方法 前言 本系列文章将介绍python提供的字符串函数,并尝试使用C++来实现这些函数.这些C++函数在这里做单独的分析,最后我 ...

随机推荐

  1. ab 轻量的压测工具

    阅读:http://www.cnblogs.com/luminji/archive/2011/09/02/2163525.html

  2. 【Android开发实践】android.view.InflateException: Binary XML file line #12: Error inflating class fragment问题解决

    一般出现的原因是fragment引入的包错了,应该是import android.app.ListFragment;而不是import android.support.v4.app.ListFragm ...

  3. 【Android学习】解决Eclipse AVD打开慢的问题

    1.创建的时候勾选“Snapshot” 2.之后Start时候勾选对应的.

  4. Redis学习 - 配置属性:protected-mode

    根据redis的说明,protected-mode在同时存在如下两种情况时触发: 1) The server is not binding explicitly to a set of address ...

  5. 【安卓】安卓res文件夹下的资源文件与R.java文件里面类的对应关系

    对于drawable.layout.menu文件夹下的每一个文件都分别会在R.java文件里面生成drawable.layout.menu类的一个常量,类名就是文件夹的名字,常量的名字就是文件名字. ...

  6. @echo off 与echo off

    echo off 关闭其他命令的显示(但是不包括自身这条命令) @echo off 关闭所有命令的显示(@关闭其后命令的显示)

  7. JavaScript——之对象参数的引用传递

    今天碰到一个问题,怎样把参数变更影响到函数外部,如: <script> var myname = "wood"; A(myname); document.write(m ...

  8. Ubuntu设置环境变量 16.04

    打开终端并输入: sudo gedit /etc/environment. 2 输入用户密码.这时输入的密码是不可见的. 3 如图,在PATH="...."的末尾处添加: :/op ...

  9. JavaScript高级程序设计学习笔记--事件

    HTML事件处理程序 <input type="button" value="Click Me" onclick"showMessage()&q ...

  10. [PHP]基本排序(冒泡排序、快速排序、选择排序、插入排序、二分法排序)

    冒泡排序: function bubbleSort($array){ $len=count($array); //该层循环控制 需要冒泡的轮数 for($i=1;$i<$len;$i++){ / ...