现在的位置: 首页 > 综合 > 正文

python中字符串操作

2014年02月01日 ⁄ 综合 ⁄ 共 6624字 ⁄ 字号 评论关闭

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:

SN Methods with Description
1 capitalize() 
Capitalizes first letter of string
2 center(width, fillchar) 
Returns a space-padded string with the original string centered to a total of width columns
3 count(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 given
3 decode(encoding='UTF-8',errors='strict') 
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
4 encode(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'.
5 endswith(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 otherwise
6 expandtabs(tabsize=8) 
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided
7 find(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 otherwise
8 index(str, beg=0, end=len(string)) 
Same as find(), but raises an exception if str not found
9 isa1num() 
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise
10 isalpha() 
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
11 isdigit() 
Returns true if string contains only digits and false otherwise
12 islower() 
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
13 isnumeric() 
Returns true if a unicode string contains only numeric characters and false otherwise
14 isspace() 
Returns true if string contains only whitespace characters and false otherwise
15 istitle() 
Returns true if string is properly "titlecased" and false otherwise
16 isupper() 
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise
17 join(seq) 
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string
18 len(string) 
Returns the length of the string
19 ljust(width[, fillchar]) 
Returns a space-padded string with the original string left-justified to a total of width columns
20 lower() 
Converts all uppercase letters in string to lowercase
21 lstrip() 
Removes all leading whitespace in string
22 maketrans() 
Returns a translation table to be used in translate function.
23 max(str) 
Returns the max alphabetical character from the string str
24 min(str) 
Returns the min alphabetical character from the string str
25 replace(old, new [, max]) 
Replaces all occurrences of old in string with new, or at most max occurrences if max given
26 rfind(str, beg=0,end=len(string)) 
Same as find(), but search backwards in string
27 rindex( str, beg=0, end=len(string)) 
Same as index(), but search backwards in string
28 rjust(width,[, fillchar]) 
Returns a space-padded string with the original string right-justified to a total of width columns.
29 rstrip() 
Removes all trailing whitespace of string
30 split(str="", num=string.count(str)) 
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given
31 splitlines( num=string.count('/n')) 
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed
32 startswith(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 otherwise
33 strip([chars]) 
Performs both lstrip() and rstrip() on string
34 swapcase() 
Inverts case for all letters in string
35 title() 
Returns "titlecased" version of string, that is, all words begin with uppercase, and the rest are lowercase
36 translate(table, deletechars="") 
Translates string according to translation table str(256 chars), removing those in the del string
37 upper() 
Converts lowercase letters in string to uppercase
38 zfill (width) 
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero)
39 isdecimal() 
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:

Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
* Repetition - Creates new strings, concatenating multiple copies of the same string 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 ell
in Membership - Returns true if a character exists in the given string H in a will give 1
not in Membership - Returns true if a character does not exist in the given string M not in a will give 1
r/R Raw String - Suppress actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the 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 first quote mark.
print r'/n' prints /n and print R'/n' prints /n
% Format - Performs String formatting See at next section

 

 

3 字符串格式化

Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

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

Symbol Functionality
* 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.
0 pad 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 the decimal point (if appl.)

抱歉!评论已关闭.