python字符串
1.常见的字符串
字符串--最常用的数据类型
(1)单引号和双引号的使用基本相同(保留空格和制表符原样)# 一般使用('或者")来创建字符串
(2)三引号--注释多行字符串
''' Hello World! What’s your name? '''
(3)转义符
例如:
-->'what\'s your name?' -->what's your name? # 在单引号(' ')中使用单引号本身(')的用法,需要指明单引号不是字符串的结尾;
-->"what's your name?" --> what's your name? # 或者是直接用双引号
-->"what\"s your name?" --> what"s your name? # 双引号字符串中直接使用双引号
-->'name\\age' --> name\age # 转义符指示反斜杠本身
-->"This is the first sentence.\
This is the second sentence." --> This is the first sentence.This is the second sentence. # 行末单独一个反斜杠表示字符串在下一行继
续
转义字符类型:https://www.runoob.com/python/python-strings.html
(4)自然字符串
指的是原来怎么样就怎么样,没有经过特别处理的字符串,比如字符串使用了反斜杠但是却没有经过转义符处理,只要指定一个自然字符串(前缀r或者R)就可以实现;
r"Newlines are indicated by \n"
(5)Unicode字符串
在字符串加上前缀u或者U(通常在使用非英语语言编辑的文本使用)
u"This is a Unicode string."
2.字符串的使用
(1)访问字符串的值
访问子字符串,可以使用[ ]截取字符串,这里有两种方法:一种是通过索引或者字符串的字符,另外一种是通过切片来截取字符串的一部分;
例如:
value = 'Hello world!' print(value[0]) --> H # 通过索引获取字符串中的字符 print(value[1:5]) --> ello # 截取字符串的一部分 print(value[:6]) --> Hello
(2)更新(修改)字符串
value = "Hello world!" print(value[:6] + 'June') --> Hello June
(3)运算符
运算符 | 描述 |
+ | 连接字符串 |
* | 重复输出字符串 |
[] | 通过索引获取字符串中字符 |
[:] | 截取字符串中的一部分 |
in | 字符串包含则返回-Ture |
not in | 字符串不包含则返回-Ture |
% | 格式字符串 |
关于文章迁CSDN
https://blog.csdn.net/weixin_40960688