---
title: "Python-字符串处理"
author: "mingren135"
date: "2012-10-20T13:04:05Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2012-10-28T21:24:36Z"
id: 1701918
url: "https://mingren135.iteye.com/blog/1701918"
---

目前为止，自己写的脚本中，用到最多的就是字符串处理，但只是业余时间写写脚本，因此会忘掉一些简单方法，在这里总结一下。

 

1）截取字符串：有2种方式，孰优孰劣显而易见

 

```
__getslice__(...)
    x.__getslice__(i, j) <==> x[i:j]

    Use of negative indices is not supported.
```

 

翻转字符串，x\[::-1]，-1是步长值

 

2）去除字符串前后空格

 

```
strip(...)  
    S.strip([chars]) -> string or unicode  
  
    Return a copy of the string S with leading and trailing  
    whitespace removed.  
    If chars is given and not None, remove characters in chars instead.  
    If chars is unicode, S will be converted to unicode before stripping  
  
lstrip(...)  
    S.lstrip([chars]) -> string or unicode  
  
rstrip(...)  
    S.rstrip([chars]) -> string or unicode 		
```

 

3）匹配字符串前、后缀

 

```
startswith(...)
    S.startswith(prefix[, start[, end]]) -> bool

    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.

endswith(...)
    S.endswith(suffix[, start[, end]]) -> bool
```

 

4）分隔、连接字符串

 

```
split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.

join(...)
    S.join(iterable) -> string

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.
```

 

5）查找字符串是否存在：还是find更习惯一些

 

```
index(...)
    S.index(sub [,start [,end]]) -> int

    Like S.find() but raise ValueError when the substring is not found.

find(...)
    S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
```

6）tiny methods

```
 #是否在其中
aa = 'shanghai'
b = 'an'
print b in aa 
print b not in aa
##连接
c = 'big'
print c + aa
##复制
print c*2
##长度
print len(aa)
##最小
print min(aa)
##最大
print max(aa)
##字母所在索引
print aa.index('a')
##统计出现次数
print aa.count('a')
```