Python中的字符串

来源:互联网 发布:怎么举报淘宝客服骂人 编辑:程序博客网 时间:2024/05/25 23:57

 

 

1 修改字符串:

例子:

#!/usr/bin/python

var1 = 'Hello World!'

print ("Updated String :- ", var1[:6] + 'Python')

python中string 可以自动用 空格连接起来。而多行字符串则可以用/表示跨行。
>>> "one" "teo" "df"
'oneteodf'
>>>

如果你不想改变串接字符串的格式,可以再输入的前面加入三个双引号 如 “““
>>> """ hello
... test
... "dfdf"
... "dfes"
... """
' hello/ntest/n"dfdf"/n"dfes"/n'

Python中的raw string
在字符串赋值的时候前面加上r即可。
>>> s=r"c:/games"
>>> s
'c://games'
>>> print s
c:/games

Python中的string可以当做对象来处理,直接调用s.fun();如s.strip()出去多余的空格。String也可以当做数组,直接用索引访问,索引可正可负。
负的从后面开始搜寻。
s[:]将输出整个字符串。

python中没有字符的概念,字符即为长度为1 的字串。

字符串的比较:
字符串也可以和数字一样进行比较,操作符类似,大小写敏感。对于字符串逻辑表达式,任何非空的字符串都可以看做true,如在or and not 中使用时遵循在各个
这个规则。

处理unicode:


Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode.

 

#!/usr/bin/python

print u'Hello, world!'

 

字符串之间的转换:

1 字符串和数字之间的转换:

int(x [,radix])

long(x [,radix])

float(x);

round(num [,digit])

complex(real [,imaginary]):转换为复数

ord(ch):转换为ascii码

 

2数字和字符串之间的转换:

1 chr(x)  unichr(x):将ascii码或者unicode转换为字符

2将数字转换为16或者8进制  oct(x)  hex(x)

3 str(obj) 将任何对象转换为字符串

Built-in String Methods:

Python includes following string method:

SNMethods with Description1capitalize()
Capitalizes first letter of string2center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns3count(str, beg= 0,end=len(string))
Counts how many times str occurs in string, or in a substring of string if starting index beg and ending index end are given3decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.4encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.5endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; Returns true if so, and false otherwise6expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided7find(str, beg=0 end=len(string))
Determine if str occurs in string, or in a substring of string if starting index beg and ending index end are given; returns index if found and -1 otherwise8index(str, beg=0, end=len(string))
Same as find(), but raises an exception if str not found9isa1num()
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise10isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise11isdigit()
Returns true if string contains only digits and false otherwise12islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise13isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise14isspace()
Returns true if string contains only whitespace characters and false otherwise15istitle()
Returns true if string is properly "titlecased" and false otherwise16isupper()
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise17join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string18len(string)
Returns the length of the string19ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width columns20lower()
Converts all uppercase letters in string to lowercase21lstrip()
Removes all leading whitespace in string22maketrans()
Returns a translation table to be used in translate function.23max(str)
Returns the max alphabetical character from the string str24min(str)
Returns the min alphabetical character from the string str25replace(old, new [, max])
Replaces all occurrences of old in string with new, or at most max occurrences if max given26rfind(str, beg=0,end=len(string))
Same as find(), but searchbackwards in string27rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string28rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total ofwidth columns.29rstrip()
Removes all trailing whitespace of string30split(str="", num=string.count(str))
Splits string according to delimiter str (space if notprovided) and returns list of substrings; split into at most num substrings if given31splitlines( num=string.count('/n'))
Splits string at all (or num) NEWLINEs and returns a list ofeach line with NEWLINEs removed32startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; Returns true if so, and false otherwise33strip([chars])
Performs both lstrip() and rstrip() on string34swapcase()
Inverts case for all letters in string35title()
Returns "titlecased" version of string, that is, all words begin with uppercase, and the rest are lowercase36translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del string37upper()
Converts lowercase letters in string to uppercase38zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero)39isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise






2字符串相关的操作符:


Assume string variable a holds 'Hello' and variable b holds 'Python' then:

OperatorDescriptionExample+Concatenation - Adds values on either side of the operator a + b will give HelloPython*Repetition - Creates new strings, concatenating multiple copies of the samestring a*2 will give -HelloHello[]Slice - Gives the character from the given index a[1] will give e[ : ]Range Slice - Gives the characters from the given range a[1:4] will give ellinMembership - Returns true if a character exists in the given string H in a will give 1not in Membership - Returns true if a character does not exist in the given string M not in a will give 1r/RRaw String - Suppress actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception ofthe raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the firstquote mark. print r'/n' prints /n and print R'/n' prints /n %Format - Performs String formatting See at next section

 

 

3 字符串格式化

Format SymbolConversion%ccharacter%sstring conversion via str() prior to formatting%isigned decimal integer%dsigned decimal integer%uunsigned decimal integer%ooctal integer%xhexadecimal integer (lowercase letters)%Xhexadecimal integer (UPPERcase letters)%eexponential notation (with lowercase 'e')%Eexponential notation (with UPPERcase 'E')%ffloating point real number%gthe shorter of %f and %e%Gthe shorter of %f and %E

Other supported symbols and functionality are listed in the following table:

SymbolFunctionality*argument specifies width or precision-left justification+display the sign<sp>leave a blank space before a positive number#add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',depending on whether 'x' or 'X' were used.0pad from left with zeros (instead of spaces)%'%%' leaves you with a single literal '%'(var)mapping variable (dictionary arguments)m.n.

m is the minimum total width and n is the number of digits to display after thedecimal point (if appl.)

原创粉丝点击