python中关于字符串的操作

首先看看str源码点进去看看 在pycharm打开关于字符串的操作有555行。那我就挑几个常用的把。毕竟那么多也用不到。而且如果要用什么平时用不到的,google一下就出来了。没必要记那么多。平时用的记熟就可以了。
看看开始的源码:class str(object):
“””
str(object=”) -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

……
str这个对象是一个类class。然后吧啦吧啦说这个str在什么情况下是正确的显示出来,一些特殊的情况等。可以百度翻译哈。
1, def capitalize(self, *args, **kwargs): # real signature unknown
“””
Return a capitalized version of the string.

    More specifically, make the first character have upper case and the rest lower
    case.
    """
    pass

str.capitalize()
以上源码三引号里面解释我这个capitalize是做什么的。有什么用,翻译过来就是这个capitalize()函数返回一个字符串大写的版本,就是使第一个字母大写,其余的小写。下面的pass就是C++写的源码,怎样实现这个首字母大写,其他字母变小写的功能。

2, def center(self, *args, **kwargs): # real signature unknown
“””
Return a centered string of length width.

    Padding is done using the specified fill character (default is a space).
    """
    pass

str.center()
返回一个字符串在中间的在设定的长度范围内。如果没有设置别的填充符号或字母,默认用空格填充。

print(‘wenDy yaNg’.capitalize()) # 设置人名的时候用的比较多
print(‘laura’.center(30, ‘-‘))
print(‘shopping list’.center(60, ‘~’))
运行结果如下:

Wendy yang
------------laura-------------
~~~~~~~~~~~~~~~~~~~~~~~shopping list~~~~~~~~~~~~~~~~~~~~~~~~

在pycharm中输入一个函数名就显示这个括号里面放什么,这个怎么截图了粘贴不上去了,晕。
3. def count(self, sub, start=None, end=None): # real signature unknown; restored from doc
“””
S.count(sub[, start[, end]]) -> int

    Return the number of non-overlapping occurrences of substring sub in
    string S[start:end].  Optional arguments start and end are
    interpreted as in slice notation.
    """
    return 0

str.count()
数这个设定的字母或字符有几个。start end要输入整数。non-overlapping非重复。slice notation切片的方法。
也是顾头不顾尾。

print('shopping list'.count('p'))
print('shopping list'.count('p', 0, 4))

运行结果如下:

2
1
       4.    def encode(self, *args, **kwargs): # real signature unknown
    """
    Encode the string using the codec registered for encoding.

      encoding
        The encoding in which to encode the string.
      errors
        The error handling scheme to use for encoding errors.
        The default is 'strict' meaning that encoding errors raise a
        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
    """
    pass
   str.encode()
   对字符串进行编码,当然是用已经注册过的编码方式。下面写了报错的一些原因,主动报错(raise a error 是主动说你这个由于什么原因等)因为什么。
   例
s1 = 'laura'
s2 = s1.encode('utf-8')  # 这一步实际把字符串类型编码成了bytes类型
print(s2)
s1 = '高新科技园'
s2 = s1.encode('utf-8')  # 把中文字符串编码成bytes类型
print(s2)
s1 = s2.decode('utf-8')
print(s1)  

运行结果如下:

b'laura' # 一个英文字符在utf-8中占1位,三个字节。但是显示的是原字符串,前面加个b
b'\xe9\xab\x98\xe6\x96\xb0\xe7\xa7\x91\xe6\x8a\x80\xe5\x9b\xad' # 一个中文字符在utf-8中占3bytes,一共是五个字,占十五位。
高新科技园
            5. def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool

        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False
        str.endswith() 
        意思就是是否以我指定的字符串结尾。suffix是词尾,结尾的意思。给个东西给我,我给你判断。可以定位,position。
        例
a = 'register_error that'.endswith('that')
print('a is : ', a)
b = 'register_error that'.endswith('tha')
print('b is : ', b)
c = 'register_error error that'.endswith('error')
print('c is : ', c)
d = 'register_error error that'.endswith('error', 0, 14)
print('d is : ', d)
运行结果
a is :  True
b is :  False
c is :  False
d is :  True

猜你喜欢

转载自blog.csdn.net/weixin_42233629/article/details/81865054