Python中的字符串

本文详细介绍Python中字符串的各种操作,包括字符串的修改、连接、格式化等,并列举了常用的字符串方法和操作符,适合Python初学者及需要复习字符串相关知识点的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

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

Python中的字符串是一种不可变的序列类型,用于表示文本数据。字符串可以通过单引号(')、双引号(")或三引号('''或""")来创建。三引号字符串可以跨越多行,常用于多行字符串和注释。 字符串Python中是序列的一种,所以它支持一些通用的序列操作,比如索引、切片、乘法和成员资格测试等。 下面是字符串的一些常见操作: 1. 索引与切片:通过索引可以访问字符串中的特定字符,通过切片可以获取字符串的一部分。 ```python s = "Hello, world!" print(s[0]) # 输出 'H' print(s[1:5]) # 输出 'ello' ``` 2. 字符串连接:可以使用加号(+)来连接两个字符串。 ```python s1 = "Hello" s2 = "world" print(s1 + ", " + s2) # 输出 'Hello, world' ``` 3. 重复:使用乘法操作符(*)可以重复字符串。 ```python print("Python" * 3) # 输出 'PythonPythonPython' ``` 4. 成员资格测试:使用in和not in来检查某个字符串是否包含在另一个字符串中。 ```python print('H' in "Hello") # 输出 True print('z' not in "Python") # 输出 True ``` 5. 转义字符:在字符串中可以使用反斜杠(\)来引入特殊字符,如换行(\n)、制表符(\t)等。 ```python print("Hello\nPython") # 输出 'Hello' 后跟一个换行,然后是 'Python' ``` 6. 原始字符串:在字符串前加上前缀r或R表示原始字符串,它不会处理字符串中的转义字符。 ```python print(r"\n") # 输出 '\n' 而不是换行 ``` 7. 字符串方法:Python提供了许多字符串方法,例如upper(), lower(), split(), replace(), find(), format()等,用于处理字符串数据。 ```python s = "hello, world" print(s.upper()) # 输出 'HELLO, WORLD' print(s.split(",")) # 输出 ['hello', ' world'] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惹不起的程咬金

来都来了,不赏点银子么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值