对 Python 字符串 学习简要总结
- Python对字符串的操作包括 '…' ,"…" ,' ' '…' ' '," " "…" " ",“+”,“*”,用于转义的“ \ ”,索引text[1],切片text[1:2],字符串长度len()等;
- '…'和"…"基本上是相同的,只能处理单行字符串;
>>> 'hallo word' 'hallo word' >>> "hallo 'python'" "hallo 'python'" >>>
- '''…'''和"""…"""基本上同样是相同的,不同于单重引号的是可以处理多行字符串,在第一行末尾添加 \ 可以防止行结尾包含在字符串内;
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) ##这个不太懂 求大神帮忙解答纠正
- “ \ 用于转义,用来表示一些特殊的符号,如果使用原始字符串的话,需要在字符串前面添加“r”;
>>> print('C:\some\name') # here \n means newline! C:\some ame >>> print(r'C:\some\name') # note the r before the quote C:\some\name
- “+”可以让两个或以上字符串相连,相邻的两个或多个字符串会自动相连在一起,“*”可以让字符串重复出现,只适用于字面值,不适用于变量和表达式;
>>> # 3 times 'un', followed by 'ium' >>> 3 * 'un' + 'ium' 'unununium' >>> >>> 'Py' 'thon' 'Python'
- python支持字符串索引,使用word[1]来索引,索引只可以获得单个字符,第一个字符串的索引为0,并且索引可以为负数,从右到左,python的索引是不可变的;
>>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[5] # character in position 5 'n' >>> >>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] 'P'
- 同样的python也支持切片,使用word[1:3]来切片,切片会让你获得一个字符串,索引总包括开头,又排除结尾,所以word[:2]+word[2:]始终等于word,Python的切片是不可变得;
>>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho'
>>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python'
- Python中常用len()计算字符串长度;
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
参考 Python中文文档