美文网首页Python🐍
python - string(2)

python - string(2)

作者: Pingouin | 来源:发表于2020-10-11 03:39 被阅读0次
  • 打标点符号前要加 \
  • 如果想输入很长的字符串(需要换行),用 ''' ''' 即triple-quoted可解决
  • \n 换行 \t tab
  • ord('a') 查字符对应的在UTF-8表中的数字 chr(97) 查UTF-8表中对应的字符

早期计算编码由英语国家主导,原始ASCII编码只有128个,不够编码欧洲语言,更不用说中文了:D
python3的默认编码是utf-8. ASCII是utf-8的子集。
万维网上大约一半的页面都以UTF-8编码。

  • index从0开始数,注意string[index]的范围不能超出
  • slice:string[0:10:-1] 范围包括0不包括10倒着数
  • iterable. for char in 'Hi mom':
  • concatention(+) and repetition(*)
  • 字符串比较 ‘a’<'b'
'abc'<'cde' # different at index 0, 'a'< 'c' True
'abc'<'abd' # different at index 2, 'c'< 'd' True
'abc'<'abcd' # 'abc' equal up to 'd' but shorter than 'abcd' True
''<'a' # the empty string's length is 0, always smaller True
  • 'a' in 'abc' #返回True
  • strings是immutable

String Method

  • string.find('a') 在字符串中寻找a,返回第一个找到的index,找不到就会返回-1
hello_word = 'hello.  world'
hello_word.find('l') #2
hello_word.find('a') #-1
#注意找不到返回的是-1而不是0是因为0可以表示第一个index
#find('t',1,6) searches for 't' in the index range 1–6
  • chaining of method: string.upper().find('a') 从左到右的顺序运行
  • nesting:嵌套,方便寻找下一个
hello_word = 'hello.  world'
hello_word.find('l',hello_word.find('l')+2)

输出格式

  • {:[align] [minimum width] [.precision] [descriptor]}



print("Pi is {:8.4f}".format(math.pi)) # 8 width 4位小数
print("{:8.2%}".format(2/3)) # 百分数形式 8 width 2位小数
print('{0} is {2} and {0} is also {1}'.format('Bill',25,'tall')) 
#Bill is tall and Bill is also 25

control and string

  • for index, letter in enumerate(river):
  • string.split() 默认是以空格分开,也可以改成用逗号分开:string.split(',')

string.punctuation:'!"# $%&'()*+,-./:;<=>?@[\]ˆ_`{} ̃'|
string.digits: '0123456789'
string.ascii_lowercase: 'abcdefghijklmnopqrstuvwxyz'
string.whitespace: '\t\n\x0b\x0c\r '

  • 'abbc'.replace('b','z') 如果想移除掉一个字母可以用replace('a','')使用空string代替

相关文章

网友评论

    本文标题:python - string(2)

    本文链接:https://www.haomeiwen.com/subject/eopspktx.html