GVKun编程网logo

python 之 string () 模块(python中string模块)

18

在本文中,您将会了解到关于python之string()模块的新资讯,同时我们还将为您解释python中string模块的相关在本文中,我们将带你探索python之string()模块的奥秘,分析py

在本文中,您将会了解到关于python 之 string () 模块的新资讯,同时我们还将为您解释python中string模块的相关在本文中,我们将带你探索python 之 string () 模块的奥秘,分析python中string模块的特点,并给出一些关于Python String .strip() 函数返回错误的输出、python string methods 和 string module区别、Python String startswith() Method、python string strip 和split的实用技巧。

本文目录一览:

python 之 string () 模块(python中string模块)

python 之 string () 模块(python中string模块)

common string oprations
import string
1. string constants (常量)

1) string.ascii_letters
      The concatenation of the  ascii_lowercase and  ascii_uppercase constants described below. This value is not locale-dependent.
print string.ascii_letters
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

2) string.ascii_lowercase
      The lowercase letters ''abcdefghijklmnopqrstuvwxyz''. This value is not locale-dependent and will not change.

3) string.ascii_uppercase
      The uppercase letters ''ABCDEFGHIJKLMNOPQRSTUVWXYZ''. This value is not locale-dependent and will not change.
4) string.digits 十进制
      The string ''0123456789''.

5) string.hexdigits 十六进制
    The string ''0123456789abcdefABCDEF''.
6) string.letters
    The concatenation of the strings lowercase and uppercase described below. The specific value is locale-dependent, and will be updated when locale.setlocale() is called.

print string.letters
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

7) string.lowercase
    A string containing all the characters that are considered lowercase letters. On most systems this is the string ''abcdefghijklmnopqrstuvwxyz''. Do not change its definition — the effect on the routines upper() and swapcase() is undefined. The specific value is locale-dependent, and will be updated when locale.setlocale() is called.

8) string.octdigits 八进制
    The string ''01234567''.

9) string.punctuation 标点符号
    String of ASCII characters which are considered punctuation characters in the C locale.

10) string.printable 所有可打印的字符集,包含数字,字母,标点空白符
    String of characters which are considered printable. This is a combination of digits, letters, punctuation, and whitespace.
print string.printable
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~

11) string.uppercase
    A string containing all the characters that are considered uppercase letters. On most systems this is the string ''ABCDEFGHIJKLMNOPQRSTUVWXYZ''. Do not change its definition — the effect on the routines lower() and swapcase() is undefined. The specific value is locale-dependent, and will be updated when locale.setlocale() is called.

12) string.whitespace 所有的空白符包含
\t  制表符
\n 换行符 (linefeed)

\x0b 

\x0C
\r 不要改变这个定义──因为所影响它的方法 strip () 和 split () 为被定义

    A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and vertical tab. Do not change its definition — the effect on the routines strip() and split() is undefined.
print string.whitespace

2. string Method (方法)
Below are listed the string methods which both 8-bit strings and Unicode objects support. Note that none of these methods take keyword arguments.

In addition, Python’s strings support the sequence type methods described in the Sequence Types — str, unicode, list, tuple, buffer, xrange section. To output formatted strings use template strings or the % operator described in the String Formatting Operations section. Also, see the re module for string functions based on regular expression_rs.

str.capitalize () 将字符串的第一个字母变成大写,其他字母变小写
    Return a copy of the string with only its first character capitalized.
    For 8-bit strings, this method is locale-dependent.
str.center(width[, fillchar])
    Return centered in a string of length width. Padding is done using the specified fillchar (default is a space).
    Changed in version 2.4: Support for the fillchar argument.
str.count (sub [, start [, end]]) 返回 sub 子串的数量
    Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
str.decode ([encoding [, errors]]) 解码
    Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is ''strict'', meaning that encoding errors raise UnicodeError. Other possible values are ''ignore'', ''replace'' and any other name registered via codecs.register_error(), see section Codec Base Classes.
str.encode ([encoding [, errors]]) 编码
    Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is ''strict'', meaning that encoding errors raise a UnicodeError. Other possible values are ''ignore'', ''replace'', ''xmlcharrefreplace'', ''backslashreplace'' and any other name registered via codecs.register_error(), see section Codec Base Classes. For a list of possible encodings, see section Standard Encodings.
str.endswith (suffix [, start [, end]]) 检查字符串是否 suffix 来结尾的,是返回 true, 否返回 false.
    Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.
str.expandtabs([tabsize])
    Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. The column number is reset to zero after each newline occurring in the string. If tabsize is not given, a tab size of 8 characters is assumed. This doesn’t understand other non-printing characters or escape sequences.
str.find (sub [, start [, end]]) 在字符串中查找 sub, 找到后返回位置,没找到返回 - 1.
    Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
str.format(format_string, *args, **kwargs)
    Perform a string formatting operation. The format_string argument can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of format_string where each replacement field is replaced with the string value of the corresponding argument.
    >>> "The sum of 1 + 2 is {0}".format(1+2)
    ''The sum of 1 + 2 is 3''
    See Format String Syntax for a description of the various formatting options that can be specified in format strings.
    This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.
str.index (sub [, start [, end]]) 功能和 find 类似,只是当没有发现的时候返回报错
    Like find(), but raise ValueError when the substring is not found.
str.isalnum () 判断字符产是英文或数字组成的
    Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
    For 8-bit strings, this method is locale-dependent.
str.isalpha()
    Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
    For 8-bit strings, this method is locale-dependent.
str.isdigit()
    Return true if all characters in the string are digits and there is at least one character, false otherwise.
    For 8-bit strings, this method is locale-dependent.
str.islower()
    Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
    For 8-bit strings, this method is locale-dependent.
str.isspace()
    Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
    For 8-bit strings, this method is locale-dependent.
str.istitle()
    Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.
    For 8-bit strings, this method is locale-dependent.
str.isupper()
    Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
    For 8-bit strings, this method is locale-dependent.
str.join(seq)
    Return a string which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method.
str.ljust(width[, fillchar])
    Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
    Changed in version 2.4: Support for the fillchar argument.
str.lower()
    Return a copy of the string converted to lowercase. 将字符串转换成小写
    For 8-bit strings, this method is locale-dependent.
str.lstrip([chars])
    Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:
    >>> ''   spacious   ''.lstrip()
    ''spacious   ''
    >>> ''www.example.com''.lstrip(''cmowz.'')
    ''example.com''
    Changed in version 2.2.2: Support for the chars argument.
str.partition(sep)
    Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

    New in version 2.5.

str.replace(old, new[, count])
    Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

str.rfind(sub[, start[, end]])
    Return the highest index in the string 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.

str.rindex(sub[, start[, end]])
    Like rfind() but raises ValueError when the substring sub is not found.

str.rjust(width[, fillchar])

    Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).

    Changed in version 2.4: Support for the fillchar argument.

str.rpartition(sep)

    Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

    New in version 2.5.

str.rsplit([sep[, maxsplit]])

    Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

    New in version 2.4.

str.rstrip([chars])

    Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

    >>> ''   spacious   ''.rstrip()
    ''   spacious''
    >>> ''mississippi''.rstrip(''ipz'')
    ''mississ''

    Changed in version 2.2.2: Support for the chars argument.

str.split([sep[, maxsplit]])

    Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).

    If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, ''1,,2''.split('','') returns [''1'', '''', ''2'']). The sep argument may consist of multiple characters (for example, ''1<>2<>3''.split(''<>'') returns [''1'', ''2'', ''3'']). Splitting an empty string with a specified separator returns [''''].

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

    For example, '' 1  2   3  ''.split() returns [''1'', ''2'', ''3''], and ''  1  2   3  ''.split(None, 1) returns [''1'', ''2   3  ''].

str.splitlines([keepends])
    Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

str.startswith(prefix[, start[, end]])

    Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

    Changed in version 2.5: Accept tuples as prefix.

str.strip([chars])

    Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

    >>> '' 

Python String .strip() 函数返回错误的输出

Python String .strip() 函数返回错误的输出

如何解决Python String .strip() 函数返回错误的输出?

我有以下字符串

''file path = data/imagery/256:0:10.0:34:26:-1478/256:0:10.0:34:26:-1478_B02_10m.tif''

我正在尝试从上面的字符串中获取 256:0:10.0:34:26:-1478_B02_10m.tif

但是如果我跑

os.path.splitext(filepath.strip(''data/imagery/256:0:10.0:34:26:-1478''))[0]

它输出''_B02_10m''

filepath.rstrip(''data/imagery/256:0:10.0:34:26:-1478'') 相同

解决方法

Python 的 strip 不会去除参数中的字符串,而是将其用作要从原始字符串中删除的字符列表,请参阅:https://docs.python.org/3/library/stdtypes.html#str.strip

编辑:这没有提供有意义的解决方案,请参阅已接受的答案。

,

假设您想要 / 之后的所有字符串数据,您始终可以使用 string.split。这会将您的字符串吐出在拆分字符串上拆分的字符串列表中。那么您将只需要此列表的最后一项。

string_var.split("/")[:-1]

在 string.split here 上查看更多官方 Python 文档。

,

你应该使用 string.split() 而不是使用 strip

以下代码为您提供所需的子字符串:

filepath = "data/imagery/256:0:10.0:34:26:-1478/256:0:10.0:34:26:-1478_B02_10m.tif"
print(filepath.split(''/'')[-1])

输出:

256:0:10.0:34:26:-1478_B02_10m.tif

python string methods 和 string module区别

python string methods 和 string module区别

python的模块真的很乱,版本之间变化多且有点随意,远没有java那么严谨,造就了它的灵活又无标准。
如string模块,从python 1.6 开始,此模块就少用了,大多函数已由标准str对象实现了。
但string的某些属性又没有被替代,如string.ascii_letters之类的,str并没有对应的替代属性.
原本不是面向对象的python,慢慢向对象靠拢,纠结.

以下内容是转帖
----------------------------------------------------------------------

python str的一些方法

在python有各种各样的string操作函数。在历史上string类在python中经历了一段轮回的历史。在最开始的时候,python有一个专门的string的module,要使用string的方法要先import,但后来由于众多的python使用者的建议,从python2.0开始,string方法改为用S.method()的形式调用,只要S是一个字符串对象就可以这样使用,而不用import。同时为了保持向后兼容,现在的python中仍然保留了一个string的module,其中定义的方法与S.method()是相同的,这些方法都最后都指向了用S.method()调用的函数。要注意,S.method()能调用的方法比string的module中的多,比如isdigit()、istitle()等就只能用S.method()的方式调用。

对一个字符串对象,首先想到的操作可能就是计算它有多少个字符组成,很容易想到用S.len(),但这是错的,应该是len(S)。因为len()是内置函数,包括在__builtin__模块中。python不把len()包含在string类型中,乍看起来好像有点不可理解,其实一切有其合理的逻辑在里头。len()不仅可以计算字符串中的字符数,还可以计算list的成员数,tuple的成员数等等,因此单单把len()算在string里是不合适,因此一是可以把len()作为通用函数,用重载实现对不同类型的操作,还有就是可以在每种有len()运算的类型中都要包含一个len()函数。python选择的是第一种解决办法。类似的还有str(arg)函数,它把arg用string类型表示出来。

字符串中字符大小写的变换:

  • S.lower()   #小写
  • S.upper()   #大写
  • S.swapcase()   #大小写互换
  • S.capitalize()   #首字母大写
  • String.capwords(S)   
    #这是模块中的方法。它把S用split()函数分开,然后用capitalize()把首字母变成大写,最后用join()合并到一起
  • S.title()    #只有首字母大写,其余为小写,模块中没有这个方法


字符串在输出时的对齐:

  • S.ljust(width,[fillchar])   
    #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。
  • S.rjust(width,[fillchar])    #右对齐
  • S.center(width, [fillchar])    #中间对齐
  • S.zfill(width)   #把S变成width长,并在右对齐,不足部分用0补足

字符串中的搜索和替换:

  • S.find(substr, [start, [end]])   
    #返回S中出现substr的第一个字母的标号,如果S中没有substr则返回-1。start和end作用就相当于在S[start:end]中搜索
  • S.index(substr, [start, [end]])   
    #与find()相同,只是在S中没有substr时,会返回一个运行时错误
  • S.rfind(substr, [start, [end]])   
    #返回S中最后出现的substr的第一个字母的标号,如果S中没有substr则返回-1,也就是说从右边算起的第一次出现的substr的首字母标号
  • S.rindex(substr, [start, [end]])
  • S.count(substr, [start, [end]])    #计算substr在S中出现的次数
  • S.replace(oldstr, newstr, [count])    
    #把S中的oldstar替换为newstr,count为替换次数。这是替换的通用形式,还有一些函数进行特殊字符的替换
  • S.strip([chars])
    #把S中前后chars中有的字符全部去掉,可以理解为把S前后chars替换为None
  • S.lstrip([chars])
  • S.rstrip([chars])
  • S.expandtabs([tabsize])   
    #把S中的tab字符替换没空格,每个tab替换为tabsize个空格,默认是8个

字符串的分割和组合:

  • S.split([sep, [maxsplit]]) 
    #以sep为分隔符,把S分成一个list。maxsplit表示分割的次数。默认的分割符为空白字符
  • S.rsplit([sep, [maxsplit]])
  • S.splitlines([keepends])
    #把S按照行分割符分为一个list,keepends是一个bool值,如果为真每行后而会保留行分割符。
  • S.join(seq) #把seq代表的序列──字符串序列,用S连接起来


字符串的mapping,这一功能包含两个函数:

  • String.maketrans(from, to) 
    #返回一个256个字符组成的翻译表,其中from中的字符被一一对应地转换成to,所以from和to必须是等长的。
  • S.translate(table[,deletechars]) 
    #使用上面的函数产后的翻译表,把S进行翻译,并把deletechars中有的字符删掉。需要注意的是,如果S为unicode字符串,那么就不支持deletechars参数,可以使用把某个字符翻译为None的方式实现相同的功能。此外还可以使用codecs模块的功能来创建更加功能强大的翻译表。

字符串还有一对编码和解码的函数:

  • S.encode([encoding,[errors]])
    #其中encoding可以有多种值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默认值为"strict",意思是UnicodeError。可能的值还有''ignore'', ''replace'', ''xmlcharrefreplace'', ''backslashreplace'' 和所有的通过codecs.register_error注册的值。这一部分内容涉及codecs模块,不是特明白
  • S.decode([encoding,[errors]])

字符串的测试函数,这一类函数在string模块中没有,这些函数返回的都是bool值:

  • S.startwith(prefix[,start[,end]]) 
    #是否以prefix开头
  • S.endwith(suffix[,start[,end]]) 
    #以suffix结尾
  • S.isalnum() 
    #是否全是字母和数字,并至少有一个字符
  • S.isalpha() #是否全是字母,并至少有一个字符
  • S.isdigit() #是否全是数字,并至少有一个字符
  • S.isspace() #是否全是空白字符,并至少有一个字符
  • S.islower() #S中的字母是否全是小写
  • S.isupper() #S中的字母是否便是大写
  • S.istitle() #S是否是首字母大写的


字符串类型转换函数,这几个函数只在string模块中有:

  • string.atoi(s[,base]) 
    #base默认为10,如果为0,那么s就可以是012或0x23这种形式的字符串,如果是16那么s就只能是0x23或0X12这种形式的字符串
  • string.atol(s[,base]) #转成long
  • string.atof(s[,base]) #转成float


这里再强调一次,字符串对象是不可改变的,也就是说在python创建一个字符串后,你不能把这个字符中的某一部分改变。任何上面的函数改变了字符串后,都会返回一个新的字符串,原字串并没有变。其实这也是有变通的办法的,可以用S=list(S)这个函数把S变为由单个字符为成员的list,这样的话就可以使用S[3]=''a''的方式改变值,然后再使用S=" ".join(S)还原成字符串

Python String startswith() Method

Python String startswith() Method

一,摘自官方API  https://docs.python.org/3/library/stdtypes.html#methods

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return Falseprefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

二,摘自 https://www.runoob.com/python/att-string-startswith.html

描述:

Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

startswith()方法语法:

str.startswith(str, beg=0,end=len(string))

参数:

  • str -- 检测的字符串。
  • strbeg -- 可选参数用于设置字符串检测的起始位置。
  • strend -- 可选参数用于设置字符串检测的结束位置。

返回值:

如果检测到字符串则返回True,否则返回False。

实例:

#!/usr/bin/python

str = "this is string example....wow!!!";
print str.startswith( ''this'' );
print str.startswith( ''is'', 2, 4 );
print str.startswith( ''this'', 2, 4 );

结果:

True
True
False

 

拓展:

有多个指定开头的字符串需要判断时,可以给prefix参数传一个元组

示例:

str1 = ''a-123''
str2 = ''b-123''
str3 = ''c-123''
str4 = ''d-123''

pre_list = [''a'', ''b'']
pre_tuple = (''a'', ''b'')
print(str1.startswith(tuple(pre_list)))
print(str2.startswith(pre_tuple))
print(str3.startswith(pre_tuple))
print(str4.startswith(tuple(pre_list)))

结果:

True
True
False
False

 

备注:tuple类型和list类型可以互转~~

元组与列表的区别在于:元组比列表的运算速度快,而且元组的数据比较安全。元组是不可改变的,为了保护其内容不被外部接口修改,不具有 append,extend,remove,pop,index这些功能;而列表是可更改的。所有有些时候我们需要两者相互转换,tuple()相当于冻结一个列表,而list()相当于解冻一个元组。可以根据需要定义

 

python string strip 和split

python string strip 和split

python strip() 函数和 split() 函数的详解及实例

python strip() 函数和 split() 函数的详解及实例

一直以来都分不清楚strip和split的功能,实际上strip是删除的意思;而split则是分割的意思。因此也表示了这两个功能是完全不一样的,strip可以删除字符串的某些字符,而split则是根据规定的字符将字符串进行分割。下面就详细说一下这两个功能,

1 Python strip()函数 介绍

函数原型

声明:s为字符串,rm为要删除的字符序列

s.strip(rm)       删除s字符串中开头、结尾处,位于 rm删除序列的字符

s.lstrip(rm)      删除s字符串中开头处,位于 rm删除序列的字符

s.rstrip(rm)     删除s字符串中结尾处,位于 rm删除序列的字符

注意:

(1)当rm为空时,默认删除空白符(包括'\n', '\r', '\t',  ' ')

(2)这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。

例如,

1

2

3

4

5

>>> a = '  123'

>>> a

'  123'

>>> a.strip()

'123'

 

 

 

 

(2)这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。

例如,

 

1

2

3

4

5

>>> a = '123abc'

>>> a.strip('21')

'3abc'

>>> a.strip('12')

'3abc'

 

 

 

结果是一样的。

2 python split()函数 介绍

说明:

Python中没有字符类型的说法,只有字符串,这里所说的字符就是只包含一个字符的字符串!!!

这里这样写的原因只是为了方便理解,仅此而已。

(1)按某一个字符分割,如‘.'

1

2

3

4

5

6

>>> str = ('www.google.com')

>>> print str

www.google.com

>>> str_split = str.split('.')

>>> print str_split

['www', 'google', 'com']

 

 

 

 

 

(2)按某一个字符分割,且分割n次。如按‘.'分割1次

1

2

3

>>> str_split = str.split('.',1)

>>> print str_split

['www', 'google.com']

 

 

 

(3)split()函数后面还可以加正则表达式,例如:

1

2

3

>>> str_split = str.split('.')[0]

>>> print str_split

www

 

 

split分隔后是一个列表,[0]表示取其第一个元素;

 

1

2

3

4

5

6

>>> str_split = str.split('.')[::-1]

>>> print str_split

['com', 'google', 'www']

>>> str_split = str.split('.')[::]

>>> print str_split

['www', 'google', 'com']

 

 

 

 

按反序列排列,[::]安正序排列

1

2

3

4

5

6

7

8

9

>>> str = str + '.com.cn'

>>> str

'www.google.com.com.cn'

>>> str_split = str.split('.')[::-1]

>>> print str_split

['cn', 'com', 'com', 'google', 'www']

>>> str_split = str.split('.')[:-1]

>>> print str_split

['www', 'google', 'com', 'com']

 

 

 

 

 

 

从首个元素开始到次末尾,最后一个元素删除掉。

split()函数典型应用之一,ip数字互换:

# ip ==> 数字

1

2

3

>>> ip2num = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])

>>> ip2num('192.168.0.1')

3232235521

 

 

 

# 数字 ==> ip # 数字范围[0, 255^4]

1

2

3

>>> num2ip = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])

>>> num2ip(3232235521)

'192.168.0.1'

 

 

 

 

最后,python怎样将一个整数与IP地址相互转换?

1

2

3

4

5

6

7

>>> import socket

>>> import struct

>>> int_ip = 123456789

>>> socket.inet_ntoa(struct.pack(‘I',socket.htonl(int_ip)))#整数转换为ip地址

‘7.91.205.21'

>>> str(socket.ntohl(struct.unpack(“I”,socket.inet_aton(“255.255.255.255″))[0]))#ip地址转换为整数

‘4294967295'

 

关于python 之 string () 模块python中string模块的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Python String .strip() 函数返回错误的输出、python string methods 和 string module区别、Python String startswith() Method、python string strip 和split等相关内容,可以在本站寻找。

本文标签: