博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中字符串操作
阅读量:4052 次
发布时间:2019-05-25

本文共 6908 字,大约阅读时间需要 23 分钟。

1 修改字符串:

例子:

#!/usr/bin/pythonvar1 = '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 sc:/gamesPython中的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  
Capitalizes first letter of string
2  
Returns a space-padded string with the original string centered to a total of width columns
3  
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  
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
4  
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.
5  
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  
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided
7  
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  
Same as find(), but raises an exception if str not found
9  
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise
10  
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
11  
Returns true if string contains only digits and false otherwise
12  
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
13  
Returns true if a unicode string contains only numeric characters and false otherwise
14  
Returns true if string contains only whitespace characters and false otherwise
15  
Returns true if string is properly "titlecased" and false otherwise
16  
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise
17  
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string
18  
Returns the length of the string
19  
Returns a space-padded string with the original string left-justified to a total of width columns
20  
Converts all uppercase letters in string to lowercase
21  
Removes all leading whitespace in string
22  
Returns a translation table to be used in translate function.
23  
Returns the max alphabetical character from the string str
24  
Returns the min alphabetical character from the string str
25  
Replaces all occurrences of old in string with new, or at most max occurrences if max given
26  
Same as find(), but search backwards in string
27  
Same as index(), but search backwards in string
28  
Returns a space-padded string with the original string right-justified to a total of width columns.
29  
Removes all trailing whitespace of string
30  
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given
31  
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed
32  
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  
Performs both lstrip() and rstrip() on string
34  
Inverts case for all letters in string
35  
Returns "titlecased" version of string, that is, all words begin with uppercase, and the rest are lowercase
36  
Translates string according to translation table str(256 chars), removing those in the del string
37  
Converts lowercase letters in string to uppercase
38  
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero)
39  
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.)

转载地址:http://pnxci.baihongyu.com/

你可能感兴趣的文章
React Native(七):Android双击Back键退出应用
查看>>
Android自定义apk名称、版本号自增
查看>>
adb command not found
查看>>
Xcode 启动页面禁用和显示
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Clone Graph(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
java自定义容器排序的两种方法
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
AngularJS2中最基本的文件说明
查看>>
从头开始学习jsp(2)——jsp的基本语法
查看>>
使用与或运算完成两个整数的相加
查看>>
备忘:java中的递归
查看>>