Python-Strings

Strings


介绍

String是Python中最常用的类型。仅仅用引号括起字符就可以创建string变量。字符串使用单引号或双引号对Python来说是一样的。

var1 = 'Hello World!'
var2 = "Python Programming"

访问string的值

Python不支持单字符类型,那些长度为1的字符串因为被认为是子字符串。为了获取子字符串,可以通过索引的方式,例

var1 = 'Hello World!'
var2 = "Python Programming"
print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])

执行结果

var1[0]:  H
var2[1:5]:  ytho

更新Strings

可以通过重新分配的方式更新一个字符串,新的字符串可以跟原来的相关或与不同的字符串组合,例

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

执行结果

Updated String :-  Hello Python

转义字符

下表是可以使用反斜杠()表示的转义字符或不可以打印字符

反斜杠表示十六进制字符描述
\a0x07Bell or alert
\b0x08Backspace
\cxControl-x
\C-xControl-x
\e0x1bEscape
\f0x0cFormfeed
\M-\C-xMeta-Control-x
\n0x0aNewline
\nnnOctal notation, where n is in the range 0.7
\r0x0dCarriage return
\s0x20Space
\t0x09Tab
\v0x0bVertical tab
\xCharacter x
\xnnHexadecimal notation, where n is in the range 0.9, a.f, or A.F

String特殊操作符

假设字符串变量a表示’Hello’, 字符串b表示’Python",因此

操作符描述示例
+结合 - 在运算符的任意一侧添加值a + b 表示HelloPython
*重复 - 创建一个新的字符串,是原字符串的多次拷贝a*2 表示 HelloHello
[]切片 - 表示指定索引的字符a[1] 表示 e
[:]范围切片 - 表示指定范围的字符a[1:4] 表示 ell
in成员资格 - 如果字符在指定的字符串中返回True‘H’ in a 表示True
not in成员资格 - 如果字符不在指定的字符串中返回True‘M’ not in a 表示True
r或R原始字符串 - 放在字符串前,告诉编译器输出元素字符,不要转义,r或R都可以打开文件的路径:r"Directory"
%格式化 - 格式化字符串建议使用Format语句

三个双引号

Python的三个双引号允许字符串跨越多行,可包含特殊字符,打印出其效果。

para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print(para_str)

执行结果

this is a long string that is made up of
several lines and non-printable characters such as
TAB (   ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ 
 ], or just a NEWLINE within
the variable assignment will also show up.

Unicode字符串

通常字符串在Python中以8位ASCII码存储,而Unicode字符串以16位的统一码存储。这样就允许更多样化的字符,包括世界上大多数的语言特殊字符。

print(u'Hello, world!')

执行结果

Hello, world!

String内置方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值