python之字符串

xiaoxiao2021-02-28  114

一、字符串的声明有三种方式:单引号、双引号和三引号(包括三个单引号或三个双引号)。例如:

>>> str1 = 'hello world' >>> str2 = "hello world" >>> str3 = '''hello world''' >>> str4 = """hello world""" >>> print str1  hello world  >>> print str2  hello world  >>> print str3  hello world  >>> print str4  hello world  在python文件头声明编码格式 :#incoding=utf-8

二、字符串中一些有用的函数:

删除空格 >>> first_name = 'hannah ' >>> first_name.strip(); 'hannah' >>> name='###heres####'; >>> name '###heres####' >>> name.strip(); '###heres####' >>> name.strip('#'); 'heres'

删除一个字符串的开头或结尾,我们分别使用rstrip()或者lstrip()。

查找和替换文本 >>> long_text='hello the mm the day frist the ehww' >>> long_text.count('the') 3 >>> long_text.find('the') 6//显然这是从0开始计数的 >>> long_text.replace('ehww','the')

'hello the mm the day frist the the'

三、切片

转载请注明原文地址: https://www.6miu.com/read-57549.html

最新回复(0)