参考链接: Python成员资格和身份运算符 | in, not in, is, is not

Strings

介绍

String是Python中最常用的类型。仅仅用引号括起字符就可以创建string变量。字符串使用单引号或双引号对Python来说是一样的。

var1 = 'Hello World!'

var2 = "Python Programming"

访问string的值

Python不支持单字符类型,那些长度为1的字符串因为被认为是子字符串。为了获取子字符串,可以通过索引的方式,例

var1 = 'Hello World!'

var2 = "Python Programming"

print("var1[0]: ", var1[0])

print("var2[1:5]: ", var2[1:5])

执行结果

var1[0]:  H

var2[1:5]:  ytho

更新Strings

可以通过重新分配的方式更新一个字符串,新的字符串可以跟原来的相关或与不同的字符串组合,例

var1 = 'Hello World!'

print("Updated String :- ", var1[:6] + 'Python')

执行结果

Updated String :-  Hello Python

转义字符

下表是可以使用反斜杠()表示的转义字符或不可以打印字符

反斜杠表示十六进制字符描述\a0x07Bell or alert\b0x08Backspace\cxControl-x\C-xControl-x\e0x1bEscape\f0x0cFormfeed\M-\C-xMeta-Control-x\n0x0aNewline\nnnOctal notation, where n is in the range 0.7\r0x0dCarriage return\s0x20Space\t0x09Tab\v0x0bVertical tab\xCharacter x\xnnHexadecimal notation, where n is in the range 0.9, a.f, or A.F

String特殊操作符

假设字符串变量a表示’Hello’, 字符串b表示’Python",因此

操作符描述示例+结合 - 在运算符的任意一侧添加值a + b 表示HelloPython*重复 - 创建一个新的字符串,是原字符串的多次拷贝a*2 表示 HelloHello[]切片 - 表示指定索引的字符a[1] 表示 e[:]范围切片 - 表示指定范围的字符a[1:4] 表示 ellin成员资格 - 如果字符在指定的字符串中返回True‘H’ in a 表示Truenot in成员资格 - 如果字符不在指定的字符串中返回True‘M’ not in a 表示Truer或R原始字符串 - 放在字符串前,告诉编译器输出元素字符,不要转义,r或R都可以打开文件的路径:r"Directory"%格式化 - 格式化字符串建议使用Format语句

三个双引号

Python的三个双引号允许字符串跨越多行,可包含特殊字符,打印出其效果。

para_str = """this is a long string that is made up of

several lines and non-printable characters such as

TAB ( \t ) and they will show up that way when displayed.

NEWLINEs within the string, whether explicitly given like

this within the brackets [ \n ], or just a NEWLINE within

the variable assignment will also show up.

"""

print(para_str)

执行结果

this is a long string that is made up of

several lines and non-printable characters such as

TAB (   ) and they will show up that way when displayed.

NEWLINEs within the string, whether explicitly given like

this within the brackets [

], or just a NEWLINE within

the variable assignment will also show up.

Unicode字符串

通常字符串在Python中以8位ASCII码存储,而Unicode字符串以16位的统一码存储。这样就允许更多样化的字符,包括世界上大多数的语言特殊字符。

print(u'Hello, world!')

执行结果

Hello, world!

String内置方法

Sr.No.方法描述1capitalize() Capitalizes first letter of string2center(width, fillchar) Returns a space-padded string with the original string centered to a total of width columns3count(str, start= 0,end=len(string)) Counts how many times str occurs in string or in a substring of string if starting index start and ending index end are given.4decode(encoding=‘UTF-8’,errors=‘strict’) Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.5encode(encoding=‘UTF-8’,errors=‘strict’) Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.6endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.7expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.8find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.9index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.10isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.11isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.12isdigit() Returns true if string contains only digits and false otherwise.13islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.14isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise15isspace() Returns true if string contains only whitespace characters and false otherwise.16istitle() Returns true if string is properly “titlecased” and false otherwise.17isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.18join(seq) Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.19len(string) Returns the length of the string20ljust(width[, fillchar]) Returns a space-padded string with the original string left-justified to a total of width columns.21lower() Converts all uppercase letters in string to lowercase22lstrip() Removes all leading whitespace in string.23maketrans() Returns a translation table to be used in translate function24max(str) Returns the max alphabetical character from the string str.25min(str) Returns the min alphabetical character from the string str26replace(old, new [, max]) Replaces all occurrences of old in string with new or at most max occurrences if max given.27rfind(str, beg=0,end=len(string)) Same as find(), but search backwards in string.28rindex( str, beg=0, end=len(string)) Same as index(), but search backwards in string29rjust(width,[, fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns.30rstrip() Removes all trailing whitespace of string.31split(str="", num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given32splitlines( num=string.count(’\n’)) Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.33startswith(str, beg=0,end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.34strip([chars]) Performs both lstrip() and rstrip() on string.35swapcase() Inverts case for all letters in string.36title() Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.37translate(table, deletechars="") Translates string according to translation table str(256 chars), removing those in the del string.38upper() Converts lowercase letters in string to uppercase.39zfill (width) Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).40isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise.

[转载] Python-Strings相关推荐

  1. 化学人学python有前途吗-转载:python之蟒开启理论计算化学的新时代

    转载:python之蟒开启理论计算化学的新时代 (2014-01-23 23:04:00) 标签: python gaussian python之蟒开启理论计算化学的新时代 就像iphone和andr ...

  2. [转载] Python中NumPy简介及使用举例

    参考链接: Python中的numpy.invert NumPy是Python语言的一个扩展包.支持多维数组与矩阵运算,此外也针对数组运算提供大量的数学函数库.NumPy提供了与Matlab相似的功能 ...

  3. python将汉字转为拼音字母_科学网—[转载]python中文汉字转拼音 - 陈明杰的博文...

    将汉字转为拼音.可以用于汉字注音.排序.检索(Russian translation) . 特性根据词组智能匹配最正确的拼音. 支持多音字. 简单的繁体支持, 注音支持. 支持多种不同拼音/注音风格. ...

  4. (转载)Python 应用发布技术

    (转载)Python 应用发布技术 2011年08月09日 分类: 脚本 2009-04-08 17:05 722人阅读 评论(0) 收藏 举报 1. Python 应用发布技术收集如何 将Py应用打 ...

  5. [转载] python之路《第二篇》Python基本数据类型

    参考链接: Python中的Inplace运算符| 1(iadd(),isub(),iconcat()-) 运算符 1.算数运算: 2.比较运算: 3.赋值运算: 4.逻辑运算: 5.成员运算: 6. ...

  6. [转载] python学习笔记2--操作符,数据类型和内置功能

    参考链接: Python中的Inplace运算符| 1(iadd(),isub(),iconcat()-) 什么是操作符? 简单的回答可以使用表达式4 + 5等于9,在这里4和5被称为操作数,+被称为 ...

  7. [转载] python+selenium自动化软件测试(第3章):unittes

    参考链接: Python 集合set different() From: https://blog.csdn.net/site008/article/details/77622472 3.1 unit ...

  8. [转载] Python 内置函数 dir()

    参考链接: Python dir() 简述 在 Python 中,有大量的内置模块,模块中的定义(例如:变量.函数.类)众多,不可能全部都记住,这时 dir() 函数就非常有用了. dir() 是一个 ...

  9. [转载] python json unicode utf-8处理总结

    参考链接: Python-json 7:Unicode和非ASCII字符编码为JSON 1.直接输出字典中文 在python中经常遇见直接print dict(字典),或者dict转json,但是没有 ...

  10. [转载] python中string函数的用法_python中string模块各属性以及函数的用法

    参考链接: Python中的string.octdigits 任何语言都离不开字符,那就会涉及对字符的操作,尤其是脚本语言更是频繁,不管是生产环境还是面试考验都要面对字符串的操作. python的字符 ...

最新文章

  1. 应用 | 红黄蓝的虐童惨案,其实可以用机器学习等技术来避免
  2. [Ruby编程语言].弗拉纳根_松本行弘读书笔记
  3. Oracle PL/SQL编程之过程
  4. Mac下Git安装及配置
  5. 常用 命令类,慢慢收集
  6. 华科00年计算机考研复试机试
  7. 算法基础——冒泡与选择排序
  8. android系统性能优化(63)---Android APP 卡顿问题分析及解决方案
  9. 打工的人面对老板是没有溢价权的
  10. SPOOLing技术的再思考
  11. 数据分析基本思路及手法
  12. ModelSim的使用详解
  13. 【Linux中基于docker安装oracle及Oracle密码过期修改】
  14. GVS与唯康教育达成战略合作,共建智能家居人才培养高地
  15. 微信小程序或微信网页里关注公众号
  16. 编写第一个WOW插件
  17. 运营商价格战终于打起来了,中国联通也有19元套餐
  18. BUUCTF(web刷题记录一)
  19. WPF——鼠标悬停在按钮时,只显示文字并高亮
  20. vmbox让鼠标离开虚拟机

热门文章

  1. mysql 5.5 client 字符集_rhel4 mysql5.5 字符集_character set
  2. ffmpeg运行在服务器上,FFMPEG安装在服务器上
  3. php 下拉菜单多选get,Jquery实现select二级联动多选下拉菜单
  4. MySQL学习(5)数据库备份
  5. 【SpringBoot 2】(四)详析SpringBoot的常用注解
  6. 用户账号管理基本概念
  7. 蓝桥杯练习系统,入门训练,Java版
  8. 洛谷P4238 【模板】多项式求逆(NTT)
  9. 推荐系统之 BPR 算法及 Librec的BPR算法实现【1】
  10. centos7安装kubernetes1.9集群