Python 字符串使用

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

1.引号的使用

1.1 如果字符串中使用的引号与包含字符串的引号不同时,可以直接使用该引号。

a='''wo men' xue xi "python"'''  
print(a)

1.2 三引号包含的字符串可以直接使用换行,或者使用\n 转义字符使字符串包含换行

thr='''sfsdfa
fdasdfasd

'''
print(thr)

1.3 其它表示跨越2行或者更多行长字符串的办法

stra="sadfasdfa"+\
     "sfafdfddfsffs"
strb=("asdfdsffggg"
      "iiooooppwerrw")
print(stra)
print(strb)

2.使用原始字符串

常用的正则表达式带有很多字面意义反斜杠的字符串,通常使用原始字符串

import re
strphone=re.compile(r"^((?:[()\d+[]])?\s*\d+(?:-\d+)?)$")
print (strphone)

3、字符与Unicode编码,函数ord()、chr()、asscii()

使用内置函数ord() 可以知道某个特定字符的Unicode值(即给出Unicode编码中某个字符的整数值)

print("  print ord(`)")
print(ord('`'))

使用内置函数chr()可以将表示有效字元的任意整数转换为对应的Unicode字符。

print("print chr(96) #is '`'")
print(chr(96))

使用内置函数ascii()可以得到ASCII字符

print('''s="qwer"+chr(8734)\nprint (ascii(s))-->'qwer\u221e' ''')
s="qwer"+chr(8734)
print (ascii(s))

4、字符串分片和步距

4.1分片操作符3种使用语法格式 seq[start] seq[start:end] seq[start:end:step]

s="0123456789qwe"
s=s[:10]+"wo"+s[10:]
print(s)
print(s[::2])

4.2如果需要连接大量字符串,通常使用str.join()

print("*".join(s))

4.3字符串常用的操作方法

s.isalpha() s非空且每个字符都是字母则返回True. 同类的有s.isalnum()、s.isdigit()

s.find(t,start,end) 返回t在s中的最左位置,没有找到返回-1. str.rfind()返回最右位置、str.index(t,statr,end)

s.format(…) s.join(seq)使用s字符对seq进行拼接。

s.lower()变为小写、s.upper()变为大写

字符串替换str.replace(str1,str2) 字符串str中str1被str2替换,且返回替换后的副本

字符串分割 str.split(t,n) 返回字符串列表,在字符串t处最多分割n次。

str="I*LOVE*YOU"
print (str.split('*'))

4.4实现字符串反转两种方法:str.join()和内置函数reversed()结合使用字符串分片和步长

restr="123456789"
print("".join(reversed(restr)))
print(restr[::-1])

5、字符串格式化

使用str.fomat()进行字符串格式化,返回一个格式化后的新字符串

s="My name is'{0}' and I\'m {1}years old ".format("WM",25)
print (s)

str.format()使用字段名(关键字参数)的用法,可以传递给str.format()位置参数和关键字参数。

s="My name is {name} and I\'m {age}years old ".format(name="WM",age=25)
print (s)

猜你喜欢

转载自blog.csdn.net/wuq757693255/article/details/81160021