字符串

字符串是 Python 中最常用的数据类型,是以单引号'或双引号"括

起来的任意文本。我们可以使用引号('或")来创建字符串

#1.重复输出字符串

print('hellow'*2)

# 2. [] ,[:] 通过索引获取字符串中字符,这里和列表的

# 切片操作是相同的,具体内容见列表

print('helloworld'[2:])

# 3. in 成员运算符

# - 如果字符串中包含给定的字符返回 True

# 否则 False

print('e2l' in 'hello')

#列表里面

print(123 in [23,45,123])

#4. 格式字符串

print('Jayce is a good student')

print('%s is a good student '%'Jayce')

#5.+ 字符串的拼接

a='123'

b='abc'

c='456'

d1=a+b+c

print(d1)

# +效率低,该用join

# join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__

# """

# Concatenate any number of strings.

#

# The string whose method is called is inserted in between each given string.

# The result is returned as a new string.

#

# Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

# """

d2=''.join([a,b,c])

d3='***'.join([a,b,c])

print(d2)

print(d3)

#String的内置方法

str = "hellow Jayce {name} is {age}"

#count()统计元素个数

print(str.count("J"))

#capitalize()首字母大写

# capitalize(self, *args, **kwargs): # real signature unknown

# """

# Return a capitalized version of the string.

#

# More specifically, make the first character have upper case and the rest lower

# case.

# """

print(str.capitalize())

#center() 居中

# center(self, *args, **kwargs): # real signature unknown

# """

# Return a centered string of length width.

#

# Padding is done using the specified fill character (default is a space).

# """

print(str.center(30,'*'))

#endswith() 判断是否以某字符串结尾

# endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__

# """

# S.endswith(suffix[, start[, end]]) -> bool

#

# Return True if S ends with the specified suffix(后缀) False otherwise.

# With optional start, test S beginning at that position.

# With optional end, stop comparing S at that position.

# suffix can also be a tuple of strings to try.

# """

print(str.endswith('ce'))

#startswith() 判断是否以某字符串开头

# startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__

# """

# S.startswith(prefix[, start[, end]]) -> bool

#

# Return True if S starts with the specified prefix, False otherwise.

# With optional start, test S beginning at that position.

# With optional end, stop comparing S at that position.

# prefix can also be a tuple of strings to try.

# """

print(str.startswith('he'))

#expandtabs() 处加空格

# expandtabs(self, *args, **kwargs): # real signature unknown

# """

# Return a copy where all tab characters are expanded using spaces.

#

# If tabsize is not given, a tab size of 8 characters is assumed.

# """

print(str.expandtabs(tabsize=20))

#find() 查找一个元素,并返回其索引值

# 找不到返回 -1

# find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__

# """

# S.find(sub[, start[, end]]) -> int

#

# Return the lowest index in S where substring sub is found,

# such that sub is contained within S[start:end]. Optional

# arguments start and end are interpreted as in slice notation.

#

# Return -1 on failure.

# """

# return 0

print(str.find('J'))

#format()格式化输出

# format(self, *args, **kwargs): # known special case of str.format

# """

# S.format(*args, **kwargs) -> str

#

# Return a formatted version of S, using substitutions from args and kwargs.

# The substitutions are identified by braces ('{' and '}').

# """

print(str.format(name = '明铭',age = 23))

#format_map()

# format_map(self, mapping): # real signature unknown; restored from __doc__

# """

# S.format_map(mapping) -> str

#

# Return a formatted version of S, using substitutions from mapping.

# The substitutions are identified by braces ('{' and '}').

# """

# return ""

print(str.format_map({'name':'明铭','age':230}))

#index() 返回索引值,没有则报错

# index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__

# """

# S.index(sub[, start[, end]]) -> int

#

# Return the lowest index in S where substring sub is found,

# such that sub is contained within S[start:end]. Optional

# arguments start and end are interpreted理解 as in slice切片 notation记号,标记法.

#

# Raises ValueError when the substring is not found.

# """

# return 0

print(str.index('J'))

#isalnum()如果字符串所有字符都是文字、字母或数字则返回 True,否则返回 False

# isalnum(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is an alpha-numeric文字数的 string, False otherwise.

#

# A string is alpha-numeric if all characters in the string are alpha-numeric and

# there is at least one character in the string.

# """

print('abc123陈明铭'.isalnum()) #true

print('abc123&陈明铭'.isalnum()) #false

#isdecimal()如果字符串只包含十进制数字则返回 True 否则返回 False.

# isdecimal(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is a decimal十进位的,小数的 string, False otherwise.

#

# A string is a decimal string if all characters in the string are decimal and

# there is at least one character in the string.

# """

print('123456'.isdecimal())

print('a123456'.isdecimal())

#isnumeric()只包含数字字符,返回 True

# isnumeric(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is a numeric string, False otherwise.

#

# A string is numeric if all characters in the string are numeric and there is at

# least one character in the string.

# """

print('a123456'.isnumeric())

#isdigit()判断是否是整型数字

# isdigit(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is a digit string, False otherwise.

#

# A string is a digit string if all characters in the string are digits and there

# is at least one character in the string.

# """

print('123.456'.isdigit()) #False

#isidentifier()判断是否是有效的标识符

# isidentifier(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is a valid有效的 Python identifier, False otherwise.

#

# Use keyword.iskeyword() to test for reserved identifiers such as "def" and

# "class".

# """

print('123abc'.isidentifier())

print('abc'.isidentifier())

#islower() 判断是否全小写

# islower(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is a lowercase string, False otherwise.

#

# A string is lowercase if all cased characters in the string are lowercase and

# there is at least one cased character in the string.

# """

print('Abc'.islower())

#isupper()判断是否全大写

# isupper(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is an uppercase string, False otherwise.

#

# A string is uppercase if all cased characters in the string are uppercase and

# there is at least one cased character in the string.

# """

print('ABC'.isupper())

#isspace() 判断是否是空格

# isspace(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is a whitespace string, False otherwise.

#

# A string is whitespace空白符;空白字符;空格 if all characters in the string are whitespace and there

# is at least one character in the string.

# """

print(' '.isspace())

# #istitle() 判断是否识标题 (首字母大写)

# istitle(self, *args, **kwargs): # real signature unknown

# """

# Return True if the string is a title-cased string, False otherwise.

#

# In a title-cased string, upper- and title-case characters may only

# follow uncased characters and lowercase characters only cased ones.

# """

print(' Le Petit Prince'.istitle())

#lower()大写变小写

# lower(self, *args, **kwargs): # real signature unknown

# """ Return a copy of the string converted to lowercase. """

print(' Le Petit Prince'.lower())

#upper() 小写变大写

# upper(self, *args, **kwargs): # real signature unknown

# """ Return a copy of the string converted to uppercase. """

print(' Le Petit Prince'.upper())

#swapcase() 大写变小写,小写变大写

# swapcase(self, *args, **kwargs): # real signature unknown

# """ Convert uppercase characters to lowercase and lowercase characters to uppercase. """

print(' Le Petit Prince'.swapcase())

#ljust() 左对齐,返回长度宽度左对齐的字符串

# ljust(self, *args, **kwargs): # real signature unknown

# """

# Return a left-justified string of length width.

#

# Padding is done using the specified fill character (default is a space).

# """

print(' Le Petit Prince'.ljust(50,'*'))

#rjust()右对齐

# rjust(self, *args, **kwargs): # real signature unknown

# """

# Return a right-justified string of length width.

#

# Padding is done using the specified fill character (default is a space).

# """

print(' Le Petit Prince'.rjust(50,'*'))

#strip() 把 和 最左边和最右边的换行符 都去掉

# strip(self, *args, **kwargs): # real signature unknown

# """

# Return a copy of the string with leading and trailing whitespace remove.

#

# If chars is given and not None, remove characters in chars instead.

# """

print(' Le Petit Prince '.strip())

#rstrip()去右边

print(' Le Petit Prince '.rstrip())

#lstrip去左边

print(' Le Petit Prince '.lstrip())

print("冷大爷累了")

#string.replace(str1, str2, num=string.count(str1))

# 把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次

# replace(self, *args, **kwargs): # real signature unknown

# """

# Return a copy with all occurrences of substring old replaced by new.

#

# count

# Maximum number of occurrences to replace.

# -1 (the default value) means replace all occurrences.

#

# If the optional argument count is given, only the first count occurrences are

# replaced.

# """

print('Le Petit Prince Le Petit Prince'.replace('Le Petit Prince',"My Little Prince"))

print('Le Petit Prince Le Petit Prince'.replace('Le Petit Prince',"My Little Prince",1))

#rfind(str, beg=0,end=len(string) )

# 似于 find()函数,不过是从右边开始查找,依然从左数

print('Le Petit Prince'.rfind('P'))

#split(str="", num=string.count(str))

# 以 str 为分隔符切片字符串,如果 num有指定值,则仅分隔 num 个子字符串

# split(self, *args, **kwargs): # real signature unknown

# """

# Return a list of the words in the string, using sep as the delimiter定界符,分隔符 string.

#

# sep

# The delimiter according which to split the string.

# None (the default value) means split according to any whitespace,

# and discard empty strings from the result.

# maxsplit

# Maximum number of splits to do.

# -1 (the default value) means no limit.

# """

print('Le Petit Prince'.split(" "))

print('Le Petit Prince'.split("P"))#以字母P分割

# string.maketrans(intab, outtab])

# maketrans() 方法用于创建字符映射的转换表,对于接受两个

# 参数的最简单的调用方式,第一个参数是字符串,表示需要

# 转换的字符,第二个参数也是字符串表示转换的目标。

# max(str) 返回字符串 str 中最大的字母。

# min(str) 返回字符串 str 中最小的字母。

# string.partition(str)

# 有点像 find()和 split()的结合体,从 str 出现的第一个位置起,

# 把字符串 string 分 成 一 个 3 元 素 的 元 组

# (string_pre_str,str,string_post_str),

# 如果 string 中不包含str 则 string_pre_str == string.

# string.rpartition(str)似于 partition()函数,不过是从右边开始查找.

# string.decode(encoding='UTF-8', errors='strict')

# 以 encoding 指定的编码格式解码 string,如果出错默认报

# 一个 ValueError 的 异 常 , 除 非 errors 指 定 的 是

# 'ignore' 或 者'replace'

# string.encode(encoding='UTF-8', errors='strict')

# 以 encoding 指定的编码格式编码 string,如果出错默认报

# 一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'

# string.splitlines(num=string.count(' '))

# 按照行分隔,返回一个包含各行作为元素的列表,如果 num 指定,则仅切片 num 个行.

冷垚
原文地址:https://www.cnblogs.com/lengyao888/p/10285654.html