每天学点Python之strings

x33g5p2x  于2021-03-13 发布在 Python  
字(1.7k)|赞(0)|评价(0)|浏览(569)

在Python3中所有的字符编码都是Unicode,所以不用再担心编码问题了。

基本操作

在Python中字符串可以用单引号或者双引号中包含字符来表示,下面列一下最最基本的操作,分别是赋值、求长度、特定位置的字符和字符串连接:

  1. In[5]: s = "hello world"
  2. In[6]: len(s)
  3. Out[6]: 11
  4. In[7]: s[0]
  5. Out[7]: 'h'
  6. In[8]: s + '!'
  7. Out[8]: 'hello world!'

如果字符串很长,要跨越多行,可以用三引号将内容包含进来:

  1. In[32]: s = '''a
  2. ... b
  3. ... c
  4. ... '''
  5. In[33]: s
  6. Out[33]: 'a\nb\nc\n'

注:命令前的In/Out[n]只是表示第几条命令,没有实际意义

格式化

Python的字符串格式化非常简单,在需要插入值的地方用{n}表示,直接调用format()函数并传入相应的参数即可,注意下标是从0开始的,而且传入的参数必须大于等于需要的参数数目(多传入的会被忽略):

  1. In[10]: s = 'my name is {0}, my age is {1}'
  2. In[11]: s.format('drfish',20)
  3. Out[11]: 'my name is drfish, my age is 20'
  4. In[12]: s.format('drfish')
  5. Traceback (most recent call last):
  6. File "<ipython-input-12-305d7c657a14>", line 1, in <module>
  7. s.format('drfish')
  8. IndexError: tuple index out of range
  9. In[13]: s.format('drfish',20,22)
  10. Out[13]: 'my name is drfish, my age is 20'

如果参数非常多,用数字来表示容易产生混乱,可以使用别名表示:

  1. In[28]: '{name} is {age}. '.format(name="drfish", age=22)
  2. Out[28]: 'drfish is 22. '

再来看复杂一点的,输如的参数不仅仅是简单的值替换,而能在字符串中对其进行后续处理,如传入一个字典,可以对其取某个键的值,同理还可以使用一些复杂的对象的方法属性:

  1. In[22]: s = 'my name is {0[name]}, my age is {0[age]}'
  2. In[23]: s.format({"name":"drfish","age":20})
  3. Out[23]: 'my name is drfish, my age is 20'

此外还能对输出的格式进行规定:

  1. # 保留小数点后4位
  2. In[26]: '{0:.4} is a decimal. '.format(1/3)
  3. Out[26]: '0.3333 is a decimal. '
  4. # 用'_'补齐字符串
  5. In[27]: '{0:_^11} is a 11 length. '.format("drfish")
  6. Out[27]: '__drfish___ is a 11 length. '
  7. # 指定宽度
  8. In[30]: 'My name is {0:8}.'.format('drfish')
  9. Out[30]: 'My name is drfish .'

常用方法

大小写

字符串可以直接进行大小写的判断与转换:

  1. In[34]: 'hello'.upper()
  2. Out[34]: 'HELLO'
  3. In[35]: 'Hello'.lower()
  4. Out[35]: 'hello'
  5. In[36]: 'Hello'.isupper()
  6. Out[36]: False

分割

分割函数str.split()可以接收两个参数,一个是分割符,另一个是进行分割的数目:

  1. In[37]: 'a=1,b=2,c=3'.split('=',2)
  2. Out[37]: ['a', '1,b', '2,c=3']

计数

统计一个字符串中的某字符串的数目:

  1. In[38]: "ab c ab".count("ab")
  2. Out[38]: 2

截取

截取操作与列表相同:

  1. In[39]: "hello world"[3:8]
  2. Out[39]: 'lo wo'

相关文章