首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

Python筑基之旅-字符串(二)

  • 25-03-03 04:22
  • 2799
  • 9251
blog.csdn.net

目录

一、字符串

1、字符串的定义

1-1、使用单引号(')

1-2、使用双引号(") 

1-3、使用三引号('''或""") 

1-4、原始字符串(r'str'或R'str') 

2、字符串的语法

3、获取字符串的属性和方法

4、获取字符串的帮助信息

5、字符串的用法

5-16、isidentifier()方法

5-17、islower()方法

5-18、isnumeric()方法

5-19、isprintable()方法

5-20、isspace()方法

5-21、istitle()方法

5-22、isupper()方法

5-23、join()方法

5-24、ljust()方法

5-25、lower()方法

5-26、lstrip()方法

5-27、partition()方法

5-28、removeprefix()方法

5-29、removesuffix()方法

5-30、replace()方法

二、推荐阅读

1、Python-VBA函数之旅-str()函数

2、Python算法之旅

3、Python函数之旅

4、个人主页-神奇夜光杯-CSDN

一、字符串

1、字符串的定义

        在Python中,字符串(Str)是一种数据类型,用于存储一系列字符(文本),字符串可以包含字母、数字、标点符号和特殊字符等。

        在Python中,可以通过以下几种方式定义字符串:

1-1、使用单引号(')
  1. s1 = 'Hello, my Python World!'
  2. print(type(s1)) # 输出:
1-2、使用双引号(") 
  1. s1 = "Hello, my Python World!"
  2. print(type(s1)) # 输出:
1-3、使用三引号('''或""") 
  1. # 使用三个单引号:'''
  2. s1 = '''Hello, my Python World!'''
  3. print(type(s1)) # 输出:
  4. # 使用三个双引号:"""
  5. s1 = """Hello, my Python World!"""
  6. print(type(s1)) # 输出:
1-4、原始字符串(r'str'或R'str') 
  1. # 用r'str'
  2. path1 = r'C:\Users\Username\Documents\file.txt'
  3. print(type(path1)) # 输出:
  4. # 用r"str"
  5. path2 = r"C:\Users\Username\Documents\file.txt"
  6. print(type(path2)) # 输出:
  7. # 用r'''str'''
  8. path3 = r'''C:\Users\Username\Documents\file.txt'''
  9. print(type(path3)) # 输出:
  10. # 用r"""str"""
  11. path4 = r"""C:\Users\Username\Documents\file.txt"""
  12. print(type(path4)) # 输出:
  13. # 用R'str'
  14. path5 = R'C:\Users\Username\Documents\file.txt'
  15. print(type(path5)) # 输出:
  16. # 用R"str"
  17. path6 = R"C:\Users\Username\Documents\file.txt"
  18. print(type(path6)) # 输出:
  19. # 用R'''str'''
  20. path7 = R'''C:\Users\Username\Documents\file.txt'''
  21. print(type(path7)) # 输出:
  22. # 用R"""str"""
  23. path8 = R"""C:\Users\Username\Documents\file.txt"""
  24. print(type(path8)) # 输出:

2、字符串的语法

        Python中的字符串是由单引号(')、双引号(")或三引号(''' 或 """)括起来的字符或文本,字符串可以是ASCII字符、Unicode字符或两者都有。

3、获取字符串的属性和方法

        用dir()函数获取str所有属性和方法的列表

  1. print(dir(str))
  2. # ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
  3. # '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__',
  4. # '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
  5. # '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
  6. # 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
  7. # 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
  8. # 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex',
  9. # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

4、获取字符串的帮助信息

        用help()函数获取str的帮助信息

  1. Help on class str in module builtins:
  2. class str(object)
  3. | str(object='') -> str
  4. | str(bytes_or_buffer[, encoding[, errors]]) -> str
  5. |
  6. | Create a new string object from the given object. If encoding or
  7. | errors is specified, then the object must expose a data buffer
  8. | that will be decoded using the given encoding and error handler.
  9. | Otherwise, returns the result of object.__str__() (if defined)
  10. | or repr(object).
  11. | encoding defaults to sys.getdefaultencoding().
  12. | errors defaults to 'strict'.
  13. |
  14. | Methods defined here:
  15. |
  16. | __add__(self, value, /)
  17. | Return self+value.
  18. |
  19. | __contains__(self, key, /)
  20. | Return key in self.
  21. |
  22. | __eq__(self, value, /)
  23. | Return self==value.
  24. |
  25. | __format__(self, format_spec, /)
  26. | Return a formatted version of the string as described by format_spec.
  27. |
  28. | __ge__(self, value, /)
  29. | Return self>=value.
  30. |
  31. | __getattribute__(self, name, /)
  32. | Return getattr(self, name).
  33. |
  34. | __getitem__(self, key, /)
  35. | Return self[key].
  36. |
  37. | __getnewargs__(...)
  38. |
  39. | __gt__(self, value, /)
  40. | Return self>value.
  41. |
  42. | __hash__(self, /)
  43. | Return hash(self).
  44. |
  45. | __iter__(self, /)
  46. | Implement iter(self).
  47. |
  48. | __le__(self, value, /)
  49. | Return self<=value.
  50. |
  51. | __len__(self, /)
  52. | Return len(self).
  53. |
  54. | __lt__(self, value, /)
  55. | Return self
  56. |
  57. | __mod__(self, value, /)
  58. | Return self%value.
  59. |
  60. | __mul__(self, value, /)
  61. | Return self*value.
  62. |
  63. | __ne__(self, value, /)
  64. | Return self!=value.
  65. |
  66. | __repr__(self, /)
  67. | Return repr(self).
  68. |
  69. | __rmod__(self, value, /)
  70. | Return value%self.
  71. |
  72. | __rmul__(self, value, /)
  73. | Return value*self.
  74. |
  75. | __sizeof__(self, /)
  76. | Return the size of the string in memory, in bytes.
  77. |
  78. | __str__(self, /)
  79. | Return str(self).
  80. |
  81. | capitalize(self, /)
  82. | Return a capitalized version of the string.
  83. |
  84. | More specifically, make the first character have upper case and the rest lower
  85. | case.
  86. |
  87. | casefold(self, /)
  88. | Return a version of the string suitable for caseless comparisons.
  89. |
  90. | center(self, width, fillchar=' ', /)
  91. | Return a centered string of length width.
  92. |
  93. | Padding is done using the specified fill character (default is a space).
  94. |
  95. | count(...)
  96. | S.count(sub[, start[, end]]) -> int
  97. |
  98. | Return the number of non-overlapping occurrences of substring sub in
  99. | string S[start:end]. Optional arguments start and end are
  100. | interpreted as in slice notation.
  101. |
  102. | encode(self, /, encoding='utf-8', errors='strict')
  103. | Encode the string using the codec registered for encoding.
  104. |
  105. | encoding
  106. | The encoding in which to encode the string.
  107. | errors
  108. | The error handling scheme to use for encoding errors.
  109. | The default is 'strict' meaning that encoding errors raise a
  110. | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  111. | 'xmlcharrefreplace' as well as any other name registered with
  112. | codecs.register_error that can handle UnicodeEncodeErrors.
  113. |
  114. | endswith(...)
  115. | S.endswith(suffix[, start[, end]]) -> bool
  116. |
  117. | Return True if S ends with the specified suffix, False otherwise.
  118. | With optional start, test S beginning at that position.
  119. | With optional end, stop comparing S at that position.
  120. | suffix can also be a tuple of strings to try.
  121. |
  122. | expandtabs(self, /, tabsize=8)
  123. | Return a copy where all tab characters are expanded using spaces.
  124. |
  125. | If tabsize is not given, a tab size of 8 characters is assumed.
  126. |
  127. | find(...)
  128. | S.find(sub[, start[, end]]) -> int
  129. |
  130. | Return the lowest index in S where substring sub is found,
  131. | such that sub is contained within S[start:end]. Optional
  132. | arguments start and end are interpreted as in slice notation.
  133. |
  134. | Return -1 on failure.
  135. |
  136. | format(...)
  137. | S.format(*args, **kwargs) -> str
  138. |
  139. | Return a formatted version of S, using substitutions from args and kwargs.
  140. | The substitutions are identified by braces ('{' and '}').
  141. |
  142. | format_map(...)
  143. | S.format_map(mapping) -> str
  144. |
  145. | Return a formatted version of S, using substitutions from mapping.
  146. | The substitutions are identified by braces ('{' and '}').
  147. |
  148. | index(...)
  149. | S.index(sub[, start[, end]]) -> int
  150. |
  151. | Return the lowest index in S where substring sub is found,
  152. | such that sub is contained within S[start:end]. Optional
  153. | arguments start and end are interpreted as in slice notation.
  154. |
  155. | Raises ValueError when the substring is not found.
  156. |
  157. | isalnum(self, /)
  158. | Return True if the string is an alpha-numeric string, False otherwise.
  159. |
  160. | A string is alpha-numeric if all characters in the string are alpha-numeric and
  161. | there is at least one character in the string.
  162. |
  163. | isalpha(self, /)
  164. | Return True if the string is an alphabetic string, False otherwise.
  165. |
  166. | A string is alphabetic if all characters in the string are alphabetic and there
  167. | is at least one character in the string.
  168. |
  169. | isascii(self, /)
  170. | Return True if all characters in the string are ASCII, False otherwise.
  171. |
  172. | ASCII characters have code points in the range U+0000-U+007F.
  173. | Empty string is ASCII too.
  174. |
  175. | isdecimal(self, /)
  176. | Return True if the string is a decimal string, False otherwise.
  177. |
  178. | A string is a decimal string if all characters in the string are decimal and
  179. | there is at least one character in the string.
  180. |
  181. | isdigit(self, /)
  182. | Return True if the string is a digit string, False otherwise.
  183. |
  184. | A string is a digit string if all characters in the string are digits and there
  185. | is at least one character in the string.
  186. |
  187. | isidentifier(self, /)
  188. | Return True if the string is a valid Python identifier, False otherwise.
  189. |
  190. | Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
  191. | such as "def" or "class".
  192. |
  193. | islower(self, /)
  194. | Return True if the string is a lowercase string, False otherwise.
  195. |
  196. | A string is lowercase if all cased characters in the string are lowercase and
  197. | there is at least one cased character in the string.
  198. |
  199. | isnumeric(self, /)
  200. | Return True if the string is a numeric string, False otherwise.
  201. |
  202. | A string is numeric if all characters in the string are numeric and there is at
  203. | least one character in the string.
  204. |
  205. | isprintable(self, /)
  206. | Return True if the string is printable, False otherwise.
  207. |
  208. | A string is printable if all of its characters are considered printable in
  209. | repr() or if it is empty.
  210. |
  211. | isspace(self, /)
  212. | Return True if the string is a whitespace string, False otherwise.
  213. |
  214. | A string is whitespace if all characters in the string are whitespace and there
  215. | is at least one character in the string.
  216. |
  217. | istitle(self, /)
  218. | Return True if the string is a title-cased string, False otherwise.
  219. |
  220. | In a title-cased string, upper- and title-case characters may only
  221. | follow uncased characters and lowercase characters only cased ones.
  222. |
  223. | isupper(self, /)
  224. | Return True if the string is an uppercase string, False otherwise.
  225. |
  226. | A string is uppercase if all cased characters in the string are uppercase and
  227. | there is at least one cased character in the string.
  228. |
  229. | join(self, iterable, /)
  230. | Concatenate any number of strings.
  231. |
  232. | The string whose method is called is inserted in between each given string.
  233. | The result is returned as a new string.
  234. |
  235. | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
  236. |
  237. | ljust(self, width, fillchar=' ', /)
  238. | Return a left-justified string of length width.
  239. |
  240. | Padding is done using the specified fill character (default is a space).
  241. |
  242. | lower(self, /)
  243. | Return a copy of the string converted to lowercase.
  244. |
  245. | lstrip(self, chars=None, /)
  246. | Return a copy of the string with leading whitespace removed.
  247. |
  248. | If chars is given and not None, remove characters in chars instead.
  249. |
  250. | partition(self, sep, /)
  251. | Partition the string into three parts using the given separator.
  252. |
  253. | This will search for the separator in the string. If the separator is found,
  254. | returns a 3-tuple containing the part before the separator, the separator
  255. | itself, and the part after it.
  256. |
  257. | If the separator is not found, returns a 3-tuple containing the original string
  258. | and two empty strings.
  259. |
  260. | removeprefix(self, prefix, /)
  261. | Return a str with the given prefix string removed if present.
  262. |
  263. | If the string starts with the prefix string, return string[len(prefix):].
  264. | Otherwise, return a copy of the original string.
  265. |
  266. | removesuffix(self, suffix, /)
  267. | Return a str with the given suffix string removed if present.
  268. |
  269. | If the string ends with the suffix string and that suffix is not empty,
  270. | return string[:-len(suffix)]. Otherwise, return a copy of the original
  271. | string.
  272. |
  273. | replace(self, old, new, count=-1, /)
  274. | Return a copy with all occurrences of substring old replaced by new.
  275. |
  276. | count
  277. | Maximum number of occurrences to replace.
  278. | -1 (the default value) means replace all occurrences.
  279. |
  280. | If the optional argument count is given, only the first count occurrences are
  281. | replaced.
  282. |
  283. | rfind(...)
  284. | S.rfind(sub[, start[, end]]) -> int
  285. |
  286. | Return the highest index in S where substring sub is found,
  287. | such that sub is contained within S[start:end]. Optional
  288. | arguments start and end are interpreted as in slice notation.
  289. |
  290. | Return -1 on failure.
  291. |
  292. | rindex(...)
  293. | S.rindex(sub[, start[, end]]) -> int
  294. |
  295. | Return the highest index in S where substring sub is found,
  296. | such that sub is contained within S[start:end]. Optional
  297. | arguments start and end are interpreted as in slice notation.
  298. |
  299. | Raises ValueError when the substring is not found.
  300. |
  301. | rjust(self, width, fillchar=' ', /)
  302. | Return a right-justified string of length width.
  303. |
  304. | Padding is done using the specified fill character (default is a space).
  305. |
  306. | rpartition(self, sep, /)
  307. | Partition the string into three parts using the given separator.
  308. |
  309. | This will search for the separator in the string, starting at the end. If
  310. | the separator is found, returns a 3-tuple containing the part before the
  311. | separator, the separator itself, and the part after it.
  312. |
  313. | If the separator is not found, returns a 3-tuple containing two empty strings
  314. | and the original string.
  315. |
  316. | rsplit(self, /, sep=None, maxsplit=-1)
  317. | Return a list of the substrings in the string, using sep as the separator string.
  318. |
  319. | sep
  320. | The separator used to split the string.
  321. |
  322. | When set to None (the default value), will split on any whitespace
  323. | character (including \n \r \t \f and spaces) and will discard
  324. | empty strings from the result.
  325. | maxsplit
  326. | Maximum number of splits.
  327. | -1 (the default value) means no limit.
  328. |
  329. | Splitting starts at the end of the string and works to the front.
  330. |
  331. | rstrip(self, chars=None, /)
  332. | Return a copy of the string with trailing whitespace removed.
  333. |
  334. | If chars is given and not None, remove characters in chars instead.
  335. |
  336. | split(self, /, sep=None, maxsplit=-1)
  337. | Return a list of the substrings in the string, using sep as the separator string.
  338. |
  339. | sep
  340. | The separator used to split the string.
  341. |
  342. | When set to None (the default value), will split on any whitespace
  343. | character (including \n \r \t \f and spaces) and will discard
  344. | empty strings from the result.
  345. | maxsplit
  346. | Maximum number of splits.
  347. | -1 (the default value) means no limit.
  348. |
  349. | Splitting starts at the front of the string and works to the end.
  350. |
  351. | Note, str.split() is mainly useful for data that has been intentionally
  352. | delimited. With natural text that includes punctuation, consider using
  353. | the regular expression module.
  354. |
  355. | splitlines(self, /, keepends=False)
  356. | Return a list of the lines in the string, breaking at line boundaries.
  357. |
  358. | Line breaks are not included in the resulting list unless keepends is given and
  359. | true.
  360. |
  361. | startswith(...)
  362. | S.startswith(prefix[, start[, end]]) -> bool
  363. |
  364. | Return True if S starts with the specified prefix, False otherwise.
  365. | With optional start, test S beginning at that position.
  366. | With optional end, stop comparing S at that position.
  367. | prefix can also be a tuple of strings to try.
  368. |
  369. | strip(self, chars=None, /)
  370. | Return a copy of the string with leading and trailing whitespace removed.
  371. |
  372. | If chars is given and not None, remove characters in chars instead.
  373. |
  374. | swapcase(self, /)
  375. | Convert uppercase characters to lowercase and lowercase characters to uppercase.
  376. |
  377. | title(self, /)
  378. | Return a version of the string where each word is titlecased.
  379. |
  380. | More specifically, words start with uppercased characters and all remaining
  381. | cased characters have lower case.
  382. |
  383. | translate(self, table, /)
  384. | Replace each character in the string using the given translation table.
  385. |
  386. | table
  387. | Translation table, which must be a mapping of Unicode ordinals to
  388. | Unicode ordinals, strings, or None.
  389. |
  390. | The table must implement lookup/indexing via __getitem__, for instance a
  391. | dictionary or list. If this operation raises LookupError, the character is
  392. | left untouched. Characters mapped to None are deleted.
  393. |
  394. | upper(self, /)
  395. | Return a copy of the string converted to uppercase.
  396. |
  397. | zfill(self, width, /)
  398. | Pad a numeric string with zeros on the left, to fill a field of the given width.
  399. |
  400. | The string is never truncated.
  401. |
  402. | ----------------------------------------------------------------------
  403. | Static methods defined here:
  404. |
  405. | __new__(*args, **kwargs) from builtins.type
  406. | Create and return a new object. See help(type) for accurate signature.
  407. |
  408. | maketrans(...)
  409. | Return a translation table usable for str.translate().
  410. |
  411. | If there is only one argument, it must be a dictionary mapping Unicode
  412. | ordinals (integers) or characters to Unicode ordinals, strings or None.
  413. | Character keys will be then converted to ordinals.
  414. | If there are two arguments, they must be strings of equal length, and
  415. | in the resulting dictionary, each character in x will be mapped to the
  416. | character at the same position in y. If there is a third argument, it
  417. | must be a string, whose characters will be mapped to None in the result.

5、字符串的用法

5-16、isidentifier()函数
  1. # Python的keyword模块和str类型的一些特性可以用于判断一个字符串是否可能是一个有效的标识符(identifier,例如变量名、函数名等)
  2. # 一个有效的Python标识符需要满足以下条件:
  3. # 1、它必须以字母(包括大小写)或下划线_开始
  4. # 2、它后面可以跟任意数量的字母、数字或下划线
  5. # 3、它不能是Python的关键字
  6. # 为了检查一个字符串是否可能是有效的标识符(不考虑关键字),你可以使用正则表达式
  7. # 如果你还希望排除Python的关键字,那么你需要使用keyword模块来检查字符串是否是关键字
  8. import re
  9. import keyword
  10. def isidentifier(s):
  11. # 使用正则表达式检查字符串是否符合标识符的基本格式
  12. if not re.match(r'^[a-zA-Z_]\w*$', s):
  13. return False
  14. # 使用keyword模块检查字符串是否是Python的关键字
  15. if keyword.iskeyword(s):
  16. return False
  17. return True
  18. # 示例
  19. print(isidentifier('my_variable')) # 输出: True
  20. print(isidentifier('123abc')) # 输出: False(以数字开头)
  21. print(isidentifier('class')) # 输出: False(是关键字)
5-17、islower()方法
  1. # 1、方法:str.islower
  2. # 2、语法:str.islower()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串中的所有字符是否都是小写
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、如果字符串中的所有字符都是小写,则返回True,否则返回False
  8. # 7、示例:
  9. # 示例
  10. s1 = "hello"
  11. print(s1.islower()) # 输出: True
  12. s2 = "Hello"
  13. print(s2.islower()) # 输出: False
  14. s3 = "hello123"
  15. print(s3.islower()) # 输出: True,因为数字不是字母,不影响判断
  16. s4 = "hello World"
  17. print(s4.islower()) # 输出: False,因为包含大写字母W
  18. s5 = ""
  19. print(s5.islower()) # 输出: False,因为包含空字符串
  20. s6 = "hello\nworld"
  21. print(s6.islower()) # 输出: True,因为换行符等非字母字符,不影响判断
  22. s7 = "⅛" #(这里使用的是分数形式的数字)
  23. print(s7.isdigit()) # 输出: False,因为包含非数字字符
5-18、isnumeric()方法
  1. # 1、方法:str.isnumeric
  2. # 2、语法:str.isnumeric()
  3. # 3、参数:无
  4. # 4、功能:用来检查字符串是否只包含数字字符
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、如果字符串中的所有字符都是数字并且字符串至少包含一个字符,则返回True,否则返回False
  8. # 6-2、isnumeric()方法仅适用于Unicode数字字符,如阿拉伯数字(0-9)和一些其他Unicode数字字符,但不适用于罗马数字、百分号、千位分隔符等
  9. # 6-3、如果你需要更广泛的数字检查(包括浮点数、指数形式等),你可能需要使用正则表达式或其他方法
  10. # 7、示例:
  11. # 示例
  12. s1 = "12345"
  13. print(s1.isnumeric()) # 输出: True
  14. s2 = "123abc"
  15. print(s2.isnumeric()) # 输出: False,因为包含非数字字符
  16. s3 = "0x123"
  17. print(s3.isnumeric()) # 输出: False,因为包含非数字字符
  18. s4 = ""
  19. print(s4.isnumeric()) # 输出: False,空字符串不包含任何数字字符
  20. s5 = "123.456"
  21. print(s5.isnumeric()) # 输出: False,因为包含小数点
  22. s6 = "123 "
  23. print(s6.isnumeric()) # 输出: False,因为包含空格
5-19、isprintable()函数
  1. # 以下是一个示例函数,它检查一个字符串是否仅包含可打印的字符
  2. import unicodedata
  3. def isprintable(s):
  4. for char in s:
  5. # 获取字符的Unicode类别
  6. category = unicodedata.category(char)
  7. # 控制字符通常以'C'开头
  8. if category.startswith('C'):
  9. return False
  10. return True
  11. # 测试
  12. print(isprintable("Hello, World!")) # 输出: True
  13. print(isprintable("\nThis string contains a newline character\n")) # 输出: False
5-20、isspace()方法
  1. # 1、方法:str.isspace
  2. # 2、语法:str.isspace()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串是否只包含空白字符
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、空白字符包括空格、制表符(\t)、换行符(\n)、回车符(\r)、换页符(\f)和垂直制表符(\v)
  8. # 6-2、如果字符串中只包含空白字符,则该方法返回 True;否则返回 False
  9. # 6-3、空字符串(即没有字符的字符串)""不会返回True,因为它不含任何字符(包括空白字符),只有包含至少一个空白字符且只包含空白字符的字符串才会返回True
  10. # 7、示例:
  11. # 示例 1:只包含空格的字符串
  12. s1 = " "
  13. print(s1.isspace()) # 输出: True
  14. # 示例 2:包含非空白字符的字符串
  15. s2 = "Hello, World!"
  16. print(s2.isspace()) # 输出: False
  17. # 示例 3:包含空格和其他字符的字符串
  18. s3 = "Hello World "
  19. print(s3.isspace()) # 输出: False
  20. # 示例 4:只包含制表符的字符串
  21. s4 = "\t\t\t"
  22. print(s4.isspace()) # 输出: True
  23. # 示例 5:包含换行符的字符串
  24. s5 = "\n\n"
  25. print(s5.isspace()) # 输出: True
  26. # 示例 6:空字符串
  27. s6 = ""
  28. print(s6.isspace()) # 输出: False(空字符串不包含任何字符,因此不被认为是只包含空白字符)
5-21、istitle()方法
  1. # 1、方法:str.istitle
  2. # 2、语法:str.istitle()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串是否是一个标题化的字符串
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、一个标题化的字符串意味着字符串中的每个单词的首字母都是大写,其余字母都是小写,并且单词之间由空白字符分隔
  8. # 6-2、如果字符串是标题化的,则该方法返回True;否则返回False
  9. # 7、示例:
  10. # 示例 1:标题化的字符串
  11. s1 = "Hello World"
  12. print(s1.istitle()) # 输出: True
  13. # 示例 2:非标题化的字符串(包含大写字母但不是每个单词的首字母)
  14. s2 = "Hello world"
  15. print(s2.istitle()) # 输出: False
  16. # 示例 3:非标题化的字符串(包含小写字母开头的单词)
  17. s3 = "hello World"
  18. print(s3.istitle()) # 输出: False
  19. # 示例 4:包含非字母字符的标题化字符串
  20. s4 = "Hello-World"
  21. print(s4.istitle()) # 输出: True
  22. # 示例 5:空字符串
  23. s5 = ""
  24. print(s5.istitle()) # 输出: False,因为空字符串不包含任何字母字符
  25. # 示例 6:只包含大写字母的字符串(不是标题化,因为没有小写字母)
  26. s6 = "HELLO WORLD"
  27. print(s6.istitle()) # 输出: False
  28. # 示例 7:包含数字和其他字符的标题化字符串
  29. s7 = "The 1st Example"
  30. print(s7.istitle()) # 输出: False,因为1st以数字开头
5-22、isupper()方法
  1. # 1、方法:str.isupper
  2. # 2、语法:str.isupper()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串中的所有字母字符是否都是大写
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、如果字符串中的所有字母字符都是大写,则该方法返回True;否则返回False
  8. # 6-2、isupper()方法只关注字母字符,并忽略非字母字符(如数字、标点符号和空格),只要字符串中的所有字母字符都是大写,那么该字符串就被认为是全大写的
  9. # 7、示例:
  10. # 示例 1:全大写的字符串
  11. s1 = "HELLO WORLD"
  12. print(s1.isupper()) # 输出: True
  13. # 示例 2:包含小写字母的字符串
  14. s2 = "Hello World"
  15. print(s2.isupper()) # 输出: False
  16. # 示例 3:只包含大写字母和数字的字符串
  17. s3 = "HELLO123"
  18. print(s3.isupper()) # 输出: True,因为只检查字母字符,数字不影响结果
  19. # 示例 4:空字符串
  20. s4 = ""
  21. print(s4.isupper()) # 输出: False,因为空字符串不包含任何字母字符
  22. # 示例 5:包含非字母字符的字符串
  23. s5 = "HELLO-WORLD"
  24. print(s5.isupper()) # 输出: True,因为'-'不是字母字符,不影响结果
  25. # 示例 6:只包含小写字母的字符串
  26. s6 = "hello world"
  27. print(s6.isupper()) # 输出: False
  28. # 示例 7:包含非ASCII字符的字符串(如果它们是大写的话)
  29. s7 = "ЗДРАВСТВУЙТЕ" # 俄语中的“你好”
  30. print(s7.isupper()) # 输出: True(取决于你的Python版本和环境对Unicode的支持)
5-23、join()方法
  1. # 1、方法:str.join
  2. # 2、语法:str.join(iterable)
  3. # 3、参数:
  4. # 3-1、iterable,表示一个可迭代对象,如列表、元组或字符串迭代器,其中的元素都是字符串
  5. # 4、功能:用于将序列(如列表、元组或字符串迭代器)中的元素以指定的字符或字符串作为分隔符连接生成一个新的字符串
  6. # 5、返回值:一个新的字符串
  7. # 6、说明:
  8. # 6-1、join()方法是在作为分隔符的字符串上调用的,而不是在要连接的元素上
  9. # 7、示例:
  10. # 示例 1:使用空格作为分隔符连接字符串列表
  11. words = ["Hello", "World"]
  12. result = " ".join(words)
  13. print(result) # 输出: Hello World
  14. # 示例 2:使用逗号作为分隔符连接字符串列表
  15. items = ["apple", "banana", "cherry"]
  16. result = ", ".join(items)
  17. print(result) # 输出: apple, banana, cherry
  18. # 示例 3:使用空字符串连接列表中的字符串,相当于拼接字符串
  19. chars = ["H", "e", "l", "l", "o"]
  20. result = "".join(chars)
  21. print(result) # 输出: Hello
  22. # 示例 4:尝试使用非字符串元素进行连接会抛出TypeError
  23. numbers = [1, 2, 3]
  24. # result = " ".join(numbers) # 这行会抛出TypeError,因为numbers中的元素不是字符串
  25. # 为了避免这个错误,可以先将列表中的元素转换为字符串
  26. numbers_str = [str(num) for num in numbers]
  27. result = " ".join(numbers_str)
  28. print(result) # 输出: 1 2 3
5-24、ljust()方法
  1. # 1、方法:str.ljust
  2. # 2、语法:str.ljust(width[, fillchar])
  3. # 3、参数:
  4. # 3-1、width(必须):新字符串的长度;如果指定长度小于原始字符串的长度,则返回原始字符串
  5. # 3-2、fillchar(可选):用于填充的字符,默认为空格
  6. # 4、功能:用于返回一个原字符串左对齐,并使用指定的填充字符(默认为空格)填充至指定长度的新字符串
  7. # 5、返回值:一个指定长度的新字符串
  8. # 6、说明:
  9. # 7、示例:
  10. # 示例 1:左对齐,使用空格填充至长度为10的新字符串
  11. s = "Hello"
  12. result = s.ljust(10)
  13. print(result) # 输出: "Hello "
  14. # 示例 2:左对齐,指定填充字符为'*',填充至长度为10的新字符串
  15. s = "Hello"
  16. result = s.ljust(10, '*')
  17. print(result) # 输出: "Hello*****"
  18. # 示例 3:原字符串长度超过指定长度,直接返回原字符串
  19. s = "Hello World"
  20. result = s.ljust(10)
  21. print(result) # 输出: "Hello World",因为长度已经超过10,所以直接返回原字符串
5-25、lower()方法
  1. # 1、方法:str.lower
  2. # 2、语法:str.lower()
  3. # 3、参数:无
  4. # 4、功能:用于将字符串中的所有大写字母转换为小写字母
  5. # 5、返回值:返回一个新的字符串,其中包含原始字符串的小写版本
  6. # 6、说明:该方法不会修改原始的字符串,而是返回一个新的字符串,其中包含原始字符串的小写版本
  7. # 7、示例:
  8. # 示例 1:将字符串转换为小写
  9. s = "Hello World"
  10. lowercase_s = s.lower()
  11. print(lowercase_s) # 输出: hello world
  12. # 示例 2:字符串中已经全部是小写,不会改变结果
  13. s = "hello world"
  14. lowercase_s = s.lower()
  15. print(lowercase_s) # 输出: hello world
  16. # 示例 3:包含非字母字符的字符串,只会转换字母部分
  17. s = "Hello123World"
  18. lowercase_s = s.lower()
  19. print(lowercase_s) # 输出: hello123world
  20. # 示例 4:空字符串或只包含非字母字符的字符串,返回相同的字符串
  21. s = ""
  22. lowercase_s = s.lower()
  23. print(lowercase_s) # 输出: ""
  24. s = "!@#"
  25. lowercase_s = s.lower()
  26. print(lowercase_s) # 输出: "!@#"
5-26、lstrip()方法
  1. # 1、方法:str.lstrip
  2. # 2、语法:str.lstrip([chars])
  3. # 3、参数:
  4. # 3-1、chars(可选):指定需要去除的字符集合;如果未指定或为空,则默认去除空白字符,字符集合可以是字符串,表示要去除的字符序列
  5. # 4、功能:用于去除字符串左侧的空白字符(包括空格、换行符、制表符等)或指定的字符
  6. # 5、返回值:返回一个新的字符串,不影响原始字符串
  7. # 6、说明:如果字符串左侧没有需要去除的字符,则返回原始字符串
  8. # 7、示例:
  9. # 示例 1:去除字符串左侧的空白字符
  10. s = " Hello World "
  11. left_stripped = s.lstrip()
  12. print(left_stripped) # 输出: "Hello World "
  13. # 示例 2:指定要去除的字符集合
  14. s = "***Hello World***"
  15. left_stripped = s.lstrip("*")
  16. print(left_stripped) # 输出: "Hello World***"
  17. # 示例 3:如果字符串左侧没有要去除的字符,则返回原始字符串
  18. s = "Hello World"
  19. left_stripped = s.lstrip()
  20. print(left_stripped) # 输出: "Hello World"
  21. # 示例 4:指定要去除的字符集合中包含多个字符
  22. s = "abcHello Worldabc"
  23. left_stripped = s.lstrip("abc")
  24. print(left_stripped) # 输出: "Hello Worldabc"
5-27、partition()方法
  1. # 1、方法:str.partition
  2. # 2、语法:str.partition(sep)
  3. # 3、参数:
  4. # 3-1、sep:用于分割字符串的分隔符
  5. # 4、功能:用于将字符串分割为三部分,返回一个包含三个元素的元组,这三个元素分别是:分隔符之前的子串、分隔符本身以及分隔符之后的子串
  6. # 5、返回值:返回包含三部分(分隔符之前的部分、分隔符本身和分隔符之后的部分)的元组
  7. # 6、说明:如果字符串中不包含指定的分隔符,则返回包含原始字符串和两个空字符串的元组
  8. # 7、示例:
  9. # 示例 1:分割包含分隔符的字符串
  10. s = "Hello-World"
  11. parts = s.partition("-")
  12. print(parts) # 输出: ('Hello', '-', 'World')
  13. # 示例 2:分隔符在字符串开头
  14. s = "-Hello-World"
  15. parts = s.partition("-")
  16. print(parts) # 输出: ('', '-', 'Hello-World')
  17. # 示例 3:分隔符在字符串结尾
  18. s = "Hello-World-"
  19. parts = s.partition("-")
  20. print(parts) # 输出: ('Hello', '-', 'World-')
  21. # 示例 4:字符串中不包含分隔符
  22. s = "HelloWorld"
  23. parts = s.partition("-")
  24. print(parts) # 输出: ('HelloWorld', '', '')
  25. # 示例 5:分隔符多次出现,但只分割第一次出现的位置
  26. s = "Hello-World-Example"
  27. parts = s.partition("-")
  28. print(parts) # 输出: ('Hello', '-', 'World-Example')
5-28、removeprefix()方法
  1. # 1、方法:str.removeprefix
  2. # 2、语法:str.removeprefix(prefix)
  3. # 3、参数:
  4. # 3-1、prefix:要删除的前缀字符串
  5. # 4、功能:用于从字符串的开头删除指定的前缀(仅适用于Python 3.9及以上版本)
  6. # 5、返回值:一个新的字符串
  7. # 6、说明:如果字符串以指定的前缀开头,则返回删除前缀后的字符串;否则,返回原始字符串
  8. # 7、示例:
  9. # 示例 1:从字符串开头删除前缀
  10. s = "prefix_Hello_World"
  11. s_without_prefix = s.removeprefix("prefix_")
  12. print(s_without_prefix) # 输出: "Hello_World"
  13. # 示例 2:字符串不以指定前缀开头,返回原始字符串
  14. s = "Hello_World"
  15. s_without_prefix = s.removeprefix("prefix_")
  16. print(s_without_prefix) # 输出: "Hello_World"
  17. # 示例 3:前缀为空字符串,返回原始字符串
  18. s = "Hello_World"
  19. s_without_prefix = s.removeprefix("")
  20. print(s_without_prefix) # 输出: "Hello_World"
  21. # 示例 4:前缀与字符串相等,返回空字符串
  22. s = "prefix_"
  23. s_without_prefix = s.removeprefix("prefix_")
  24. print(s_without_prefix) # 输出: ""
5-29、removesuffix()方法
  1. # 1、方法:str.removesuffix
  2. # 2、语法:str.removesuffix(suffix)
  3. # 3、参数:
  4. # 3-1、suffix:要删除的后缀字符串
  5. # 4、功能:用于从字符串的末尾删除指定的后缀(仅适用于Python 3.9及以上版本)
  6. # 5、返回值:一个新的字符串
  7. # 6、说明:如果字符串以指定的后缀结尾,则返回删除后缀后的字符串;否则,返回原始字符串
  8. # 7、示例:
  9. # 示例 1:从字符串末尾删除后缀
  10. s = "Hello_World_suffix"
  11. s_without_suffix = s.removesuffix("_suffix")
  12. print(s_without_suffix) # 输出: "Hello_World"
  13. # 示例 2:字符串不以指定后缀结尾,返回原始字符串
  14. s = "Hello_World"
  15. s_without_suffix = s.removesuffix("_suffix")
  16. print(s_without_suffix) # 输出: "Hello_World"
  17. # 示例 3:后缀为空字符串,返回原始字符串
  18. s = "Hello_World"
  19. s_without_suffix = s.removesuffix("")
  20. print(s_without_suffix) # 输出: "Hello_World"
  21. # 示例 4:后缀与字符串相等,返回空字符串
  22. s = "_suffix"
  23. s_without_suffix = s.removesuffix("_suffix")
  24. print(s_without_suffix) # 输出: ""
5-30、replace()方法
  1. # 1、方法:str.replace
  2. # 2、语法:str.replace(old, new[, count])
  3. # 3、参数:
  4. # 3-1、old(必须):需要被替换的子串
  5. # 3-2、new(必须):用于替换的子串
  6. # 3-3、count(可选):替换的最大次数;如果省略或为-1,则替换所有出现的子串
  7. # 4、功能:用于在字符串中查找并替换指定的子串,该方法会返回一个新的字符串,其中指定的子串(或所有出现的子串)已被新的子串替换
  8. # 5、返回值:一个新的字符串
  9. # 6、说明:如果old参数指定的子串在原始字符串中不存在,则replace()方法会返回原始字符串
  10. # 7、示例:
  11. # 示例 1:替换所有出现的子串
  12. s = "Hello, world! world is beautiful."
  13. s_replaced = s.replace("world", "Python")
  14. print(s_replaced) # 输出: "Hello, Python! Python is beautiful."
  15. # 示例 2:替换指定次数的子串
  16. s = "apple, apple, apple pie"
  17. s_replaced = s.replace("apple", "orange", 2)
  18. print(s_replaced) # 输出: "orange, orange, apple pie"
  19. # 示例 3:如果子串不存在于原始字符串中,则不执行替换
  20. s = "banana, banana split"
  21. s_replaced = s.replace("apple", "orange")
  22. print(s_replaced) # 输出: "banana, banana split"(没有变化)
  23. # 示例 4:使用空字符串作为替换字符串,可以删除指定子串
  24. s = "aaa123bbb456ccc"
  25. s_replaced = s.replace("bbb", "")
  26. print(s_replaced) # 输出: "aaa123456ccc"

二、推荐阅读

1、Python-VBA函数之旅-str()函数

2、Python算法之旅

3、Python函数之旅

4、个人主页-神奇夜光杯-CSDN

文章知识点与官方知识档案匹配,可进一步学习相关知识
算法技能树首页概览61321 人正在系统学习中
遨游码海,我心飞扬
微信名片
注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/139032479"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top