第3章 使用字符串

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

3.1 字符串的基本操作
字符串不可变,元素赋值和切片赋值都是非法的。

>>> website = 'http://www.pthon.org'
>>> website[-3:] = 'com'
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    website[-3:] = 'com'
TypeError: 'str' object does not support item assignment
>>> 

3.2 设置字符串的格式:精简版
将值转化为字符串并设置其格式是一个重要的操作
1)使用字符串格式设置运算符——百分号

>>> format = "Hello,%s. %s enough for ya?"
>>> values = ('world','Hot')
>>> format % values
'Hello,world. Hot enough for ya?'
>>> 

2)模板字符串

>>> from string import Template
>>> tmp1 = Template("Hello, $who! $what enough for ya?")
>>> tmp1.substitute(who="Mars",what="Dusty")
'Hello, Mars! Dusty enough for ya?'
>>> 

3)字符串方法format
每个替换字段都用花括号括起,
* 替换字段没有名称或将索引用用作名称

>>> "{},{} and {}".format("first","second","third")
'first,second and third'
>>> "{0},{1} and {2}".format("f","s","t")
'f,s and t'
>>> 
  • 命名字段
>>> from math import pi
>>> "{name} is approximately {value:.2f}".format(value=pi,name="π")
'π is approximately 3.14'
>>> 
  • 变量与替换字段同名,在字符串前面加f
>>> from math import e
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
>>> 
>>> "Euler's constant is roughly {e}.".format(e = e)
"Euler's constant is roughly 2.718281828459045."
>>> 

3.3 设置字符串的格式:完整版

3.4 字符串方法

3.4.1 center

>>> "abc".center(9,"*")
'***abc***'
>>> "abc".center(10,"*")
'***abc****'
>>> 

3.4.2 find

>>> "abcd".find("b")
1
>>> "abcd".find("bc")
1
>>> 

3.4.3 join

>>> a = ["a","b","c"]
>>> "+".join(a)
'a+b+c'
>>> 

3.4.4 lower

>>> "ABC".lower()
'abc'
>>> "abc".upper()
'ABC'
>>> 

3.4.5 replace

>>> "abc".replace("b","d")
'adc'
>>> 

3.4.6 split

>>> "a,b,c".split(",")
['a', 'b', 'c']
>>> 

3.4.7 strip

>>> " a bc ".strip()
'a bc'
>>> 

3.4.8 translate

>>> table = str.maketrans('cs','kz')
>>> table
{99: 107, 115: 122}
>>> "this is an incredible test".translate(table)
'thiz iz an inkredible tezt'
>>> 

3.4.9 判断字符串是否满足特定的条件

>>> " abc".isspace()
False
>>> " ".isspace()
True
>>> "1".isdigit()
True
>>> "ABC".isupper()
True
>>> 

猜你喜欢

转载自blog.csdn.net/u010819416/article/details/82315944