python基础之字符串详解

1、Python环境配置:

Python官网:https://www.python.org/

Pycharm官网 http://www.jetbrains.com/pycharm/download

下载好之后安装,注意勾选环境变量。

2、写python一定要注意代码的缩进。

2、字符串:

(1)、字符串是从左到右是从0开始索引,从右到左是从-1开始。遵循包前不包后原则。

举例说明:

代码:                       解释:                                          输出结果:

a='abcdefghijk'
print a                      输出a                                           abcdefghijk
print a[0]                 输出第1个元素                               a

print a[2:5]              输出第3个到第5个元素                   cde
print a[2:]                从第3个字符开始输出字符串              cdefghijk
print a[-1]                从右往左输出第1个                         k
print a[-3:-1]           从倒数第3个开始(同样包前不包后)  ij
print a[-3:]               从倒数第3个开始到最后                   ijk
print a[:]                  输出整段字符串                               abcdefghijk
print a[3:]                从第4个字符开始                             defghijk
print a[-8:]              从右边数第8个字符开始输出               defghijk

print a*2                 输出两次                                        abcdefghijkabcdefghijk

(2)同样支持格式字符串:

举例说明:

name='Bob'

age=16

print ("%s  is  %d-year-old" %(name,age))

输出结果:Bob is 16-year-old

(3)字符串检测

举例说明:

代码:                                                        解释                                           输出结果

s = 'HelloabcdWord'                               
print s.isalpha()                                查看字符串是否全由字母组成                   True

print s.isdigit()                                 查看字符串是否全由数字组成                    False 

print s.isspace()                               查看字符串是否全由空格组成                    False
print s.startswith('Hello')                查看字符串是否以‘Hello’开头                   True
print s.endswith('World')                查看字符串是否以‘Word’结尾                   False

(3)大写与小写

举例说明:

代码:                                                        解释                                          

a = 'In\na line'                              不加r的字符串中\n会使字符串换行
b = r'In\na line'                             加r的字符串中转义字符不会被转义
print a                                             
print b
print a.lower()                                转小写
print b.upper()                                转大写

输出结果:

In
a line
In\na line
in
a line
IN\NA LINE


(3)字符串置换

 举例说明:

代码:

weather = 'rainy day'
bag = 'nothing in the bag'

if weather.find('rain')!=-1:

bag=bag.replace('nothing','umbrella')

print bag

解释:

如果匹配到 ‘rain’ 则将‘noting’只会为‘umbrella’

find函数匹配不到所找的字符返回值为‘-1’。

输出结果:

umbrella in the bag

 

今天的分享就到这个~~~~~~~

 

posted @ 2016-08-15 10:44  陈姑娘  阅读(612)  评论(3编辑  收藏  举报