Python入门(十四) 字符串

    Python中的字符串能够是单引号''或者双引号""括起来,若是字符串比较长,须要垮行,能够使用三引号''' '''
python

errHtml = '''
<HTML><HEAD><TITLE>
Python CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
'''

print(errHtml)
>>>
<HTML><HEAD><TITLE>
Python CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>

    1.格式化字符串:code

str1 = "name = %s, age = %d" % ('billy', 28)
print(str1)

>>>
name = billy, age = 28

  Python中的字符串格式化符号与c语言的很相似:
对象

1)%c: 格式化单个ascii字符ip

2)%s: ci

3)%d:字符串

4)%u:string

5)%x:it

6)%f:class

7)%p: 用十六进制格式化变量的地址变量

    2. 字符串经常使用的方法:

1)字符串查找:

    string.find(str, start=0, end=len(string));

    string.rfind;

    find方法若是找到匹配的字符串,则返回起始的下标,不然返回-1。rfind与find相似,只不过是从右边开始寻找。

str_demo = 'hello world, just do it'
print(str_demo.find('just'))
print(str_demo.find('python'))
print(str_demo.find('o'), str_demo.rfind('o'))

>>>
13
-1
4 19

2)字符串替换: replace

    string.replace(old, new, count=string,count(old))

print(str_demo.replace('world', 'Python'))

>>>
hello Python, just do it

3)字符串链接: join

#直接链接字符串
print(str_demo + ' come on')

>>>
hello Python, just do it come on
#使用join链接seq
str_nums = ['1', '2', '3']
sep = '+'
print(sep.join(str_nums))

>>>
1+2+3

4)字符串分割:split(sep) 分割为一个list

print(str_demo.split(','))

>>>
['hello world', ' just do it']

5)去除字符串两边的空格: strip

print('  hello world  '.strip())

>>>
hello world

6)大小写转换:lower, uppace

print('Hello World'.lower())
print('Hello World'.upper())

>>>
hello world
HELLO WORLD


    最后,要说明的是Python中的字符串是不可变的,上面提供的方法,是返回了一个新的字符串对象,并无修改旧的字符串对象。

相关文章
相关标签/搜索