首页 最新 热门 推荐

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

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

  • 25-03-03 04:22
  • 4808
  • 13106
blog.csdn.net

目录

一、字符串

1、字符串的定义

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

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

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

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

2、字符串的语法

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

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

5、字符串的用法

5-31、rfind()方法

5-32、rindex()方法

5-33、rjust()方法

5-34、rpartition()方法

5-35、rsplit()方法

5-36、rstrip()方法

5-37、split()方法

5-38、splitlines()方法

5-39、startswith()方法

5-40、strip()方法

5-41、swapcase()方法

5-42、titile()方法

5-43、translate()方法

5-44、upper()方法

5-45、zfill()方法

二、推荐阅读

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-31、rfind()方法
  1. # 1、方法:str.rfind
  2. # 2、语法:str.rfind(sub[, start[, end]])
  3. # 3、参数:
  4. # 3-1、sub(必须):需要被查找的子串
  5. # 3-2、start(可选):开始搜索的索引位置;默认为 -1,表示从字符串的末尾开始搜索
  6. # 3-3、end(可选):结束搜索的索引位置(不包括);默认为字符串的长度
  7. # 4、功能:用于从字符串的末尾开始查找指定的子串,并返回该子串最后出现的位置的索引;如果未找到该子串,则返回-1
  8. # 5、返回值:返回被查找子串最后出现位置的索引
  9. # 6、说明:
  10. # 6-1、与find()方法类似,但rfind()是从字符串的末尾开始搜索
  11. # 6-2、start和end参数都可以是负数,表示从字符串的末尾开始计算索引
  12. # 7、示例:
  13. # 示例1:查找子串最后出现的位置
  14. s = "Hello, world! Hello everyone."
  15. index = s.rfind("Hello")
  16. print(index) # 输出: 14,因为 "Hello" 最后一次出现在索引14的位置
  17. # 示例2:使用可选参数 start 和 end
  18. s = "apple, banana, apple pie"
  19. index = s.rfind("apple", 0, 10) # 从索引0开始,到索引10(不包括)结束搜索
  20. print(index) # 输出: 0,因为在这个范围内,"apple" 第一次(也是唯一一次)出现在索引0的位置
  21. # 示例3:未找到子串时返回 -1
  22. s = "banana, banana split"
  23. index = s.rfind("apple")
  24. print(index) # 输出: -1,因为 "apple" 没有出现在字符串中
  25. # 示例4:使用 start 的默认值从字符串末尾开始搜索
  26. s = "abcabcabc"
  27. index = s.rfind("abc", -4) # 从索引-4(即倒数第四个字符)开始搜索,这等同于从末尾开始搜索
  28. print(index) # 输出: 6,因为 "abc" 最后一次出现在索引6的位置
5-32、rindex()方法
  1. # 1、方法:str.rindex
  2. # 2、语法:str.rindex(sub[, start[, end]])
  3. # 3、参数:
  4. # 3-1、sub(必须):需要被查找的子串
  5. # 3-2、start(可选):开始搜索的索引位置;默认为 -1,表示从字符串的末尾开始搜索
  6. # 3-3、end(可选):结束搜索的索引位置(不包括);默认为字符串的长度
  7. # 4、功能:用于从字符串的末尾开始查找指定的子串,并返回该子串最后出现的位置的索引;如果未找到该子串,则会引发ValueError异常
  8. # 5、返回值:返回被查找子串最后出现位置的索引
  9. # 6、说明:
  10. # 6-1、如果子串sub存在于字符串中,rindex()会返回子串最后出现的位置的索引;如果未找到子串,则会引发ValueError异常
  11. # 7、示例:
  12. # 示例1:查找子串最后出现的位置
  13. s = "Hello, world! Hello everyone."
  14. index = s.rindex("Hello")
  15. print(index) # 输出: 14,因为"Hello"最后一次出现在索引14的位置
  16. # 示例2:使用可选参数start和end
  17. s = "apple, banana, apple pie"
  18. index = s.rindex("apple", 0, 13) # 从索引0开始,到索引13(不包括)结束搜索
  19. print(index) # 输出: 0,因为在这个范围内,"apple" 第一次(也是唯一一次)出现在索引0的位置
  20. # 示例3:未找到子串时引发 ValueError 异常
  21. s = "banana, banana split"
  22. try:
  23. index = s.rindex("apple")
  24. print(index) # 这行代码不会执行,因为会抛出异常
  25. except ValueError:
  26. print("子串未找到") # 输出: 子串未找到
  27. # 示例4:使用 start 的默认值从字符串末尾开始搜索
  28. s = "abcabcabc"
  29. index = s.rindex("abc", -4) # 从索引-4(即倒数第四个字符)开始搜索,这等同于从末尾开始搜索
  30. print(index) # 输出: 6,因为 "abc" 最后一次出现在索引6的位置
5-33、rjust()方法
  1. # 1、方法:str.rjust
  2. # 2、语法:str.rjust(width[, fillchar])
  3. # 3、参数:
  4. # 3-1、width:所需的最小宽度;如果指定了负值,则会引发ValueError
  5. # 3-2、fillchar(可选):用于填充的字符;默认为空格字符(' ')
  6. # 4、功能:用于在字符串的左侧填充指定的字符,直到达到指定的总长度
  7. # 5、返回值:一个指定长度的新字符串
  8. # 6、说明:
  9. # 7、示例:
  10. # 示例1:填充空格至指定宽度
  11. s = "hello"
  12. s_padded = s.rjust(10)
  13. print(s_padded) # 输出: ' hello'(左侧填充了5个空格)
  14. # 示例2:使用指定的填充字符
  15. s = "42"
  16. s_padded = s.rjust(5, '0')
  17. print(s_padded) # 输出: '00042'(左侧填充了3个'0')
  18. # 示例3:如果字符串已经达到或超过指定宽度,则原样返回
  19. s = "superlongstring"
  20. s_padded = s.rjust(10)
  21. print(s_padded) # 输出: 'superlongstring'(没有填充,因为原字符串已经超过了指定宽度)
5-34、rpartition()方法
  1. # 1、方法:str.rpartition
  2. # 2、语法:str.rpartition(sep)
  3. # 3、参数:
  4. # 3-1、sep:用于分割字符串的分隔符
  5. # 4、功能:用于从右边开始搜索分隔符,将字符串分割为三部分,返回一个包含三个元素的元组,这三个元素分别是:分隔符之前的子串、分隔符本身以及分隔符之后的子串
  6. # 5、返回值:返回包含三部分(分隔符之前的部分、分隔符本身和分隔符之后的部分)的元组
  7. # 6、说明:
  8. # 7、示例:
  9. # 示例1:使用分隔符进行分割
  10. s = "www.example.com"
  11. parts = s.rpartition(".")
  12. print(parts) # 输出: ('www.example', '.', 'com')
  13. # 示例2:如果分隔符不存在于字符串中
  14. s = "no_dots_here"
  15. parts = s.rpartition(".")
  16. print(parts) # 输出: ('no_dots_here', '', '')
  17. # 示例3:分隔符是字符串的一部分但不是分隔符
  18. s = "hello.world.example"
  19. parts = s.rpartition(".")
  20. print(parts) # 输出: ('hello.world', '.', 'example')
  21. # 注意这里是从右侧开始搜索,所以只找到了最右侧的"."
5-35、rsplit()方法
  1. # 1、方法:str.rsplit
  2. # 2、语法:str.rsplit(sep=None, maxsplit=-1)
  3. # 3、参数:
  4. # 3-1、sep:用于分割字符串的分隔符;默认为所有的空字符,包括空格、换行符、制表符等,如果指定了分隔符,则只会在该分隔符处进行分割
  5. # 3-2、maxsplit:分割的最大次数;默认为 -1,表示分割所有可能的子串,如果指定了maxsplit,则分割会在达到maxsplit次后停止,即使字符串中还存在分隔符
  6. # 4、功能:用于从字符串的右侧开始分割字符串。这个方法会根据指定的分隔符(sep)和最大分割次数(maxsplit,可选参数)将字符串分割为多个子串,并返回一个列表
  7. # 5、返回值:一个列表
  8. # 6、说明:
  9. # 6-1、如果sep不存在于字符串中,或者maxsplit设置为0或负数(且小于-1),则整个字符串将作为一个单独的子串返回
  10. # 6-2、如果未指定sep,则默认使用所有的空字符作为分隔符,包括但不限于包括空格、换行符、制表符等
  11. # 7、示例:
  12. # 示例1:使用空格作为分隔符
  13. s = "one two three four"
  14. parts = s.rsplit()
  15. print(parts) # 输出: ['one', 'two', 'three', 'four']
  16. # 示例2:指定分隔符和最大分割次数
  17. s = "a-b-c-d-e"
  18. parts = s.rsplit("-", 2)
  19. print(parts) # 输出: ['a-b-c', 'd', 'e']
  20. # 示例3:只指定分隔符
  21. s = "a,b,c,d,e"
  22. parts = s.rsplit(",")
  23. print(parts) # 输出: ['a', 'b', 'c', 'd', 'e']
  24. # 示例4:指定不存在的分隔符
  25. s = "no_dashes_here"
  26. parts = s.rsplit("-")
  27. print(parts) # 输出: ['no_dashes_here']
  28. # 示例5:指定分隔符和maxsplit=1
  29. s = "a,b,c,d,e"
  30. parts = s.rsplit(",", 1)
  31. print(parts) # 输出: ['a,b,c,d', 'e']
5-36、rstrip()方法
  1. # 1、方法:str.rstrip
  2. # 2、语法:str.rstrip([chars])
  3. # 3、参数:
  4. # 3-1、chars(可选):一个字符串,指定要从原始字符串的右侧删除的字符集合;如果省略或未指定,则默认删除所有尾随的空白字符
  5. # 4、功能:用于从字符串的右侧(末尾)删除指定的字符(或字符集合);默认情况下,它会删除所有尾随的空白字符(包括空格、换行符、制表符等)
  6. # 5、返回值:一个新的字符串,它是原始字符串的副本,但右侧不再包含指定的字符
  7. # 6、说明:
  8. # 6-1、如果未指定chars,则默认删除所有尾随的空白字符,返回的是处理后的新字符串,而原始字符串保持不变
  9. # 7、示例:
  10. # 示例1:删除尾随的空白字符
  11. s = " Hello, World! "
  12. s_stripped = s.rstrip()
  13. print(s_stripped) # 输出: " Hello, World!"(注意右侧的空格被删除了)
  14. # 示例2:删除尾随的指定字符
  15. s = "Hello, World!!!"
  16. s_stripped = s.rstrip("!")
  17. print(s_stripped) # 输出: "Hello, World"(注意尾随的"!"被删除了)
  18. # 示例3:删除尾随的多个字符
  19. s = "apples, oranges, and bananas,,,"
  20. s_stripped = s.rstrip(", ")
  21. print(s_stripped) # 输出: "apples, oranges, and bananas"(注意尾随的逗号和空格被删除了)
  22. # 示例4:如果指定字符不存在于末尾,则原样返回
  23. s = "Hello, World"
  24. s_stripped = s.rstrip("!")
  25. print(s_stripped) # 输出: "Hello, World"(字符串未改变,因为没有尾随的"!")
5-37、split()方法
  1. # 1、方法:str.split
  2. # 2、语法:str.split(sep=None, maxsplit=-1)
  3. # 3、参数:
  4. # 3-1、sep(可选):用于分割字符串的分隔符;默认为None,表示在任意空白处分割
  5. # 3-2、maxsplit(可选):分割的最大次数;默认为-1,表示分割所有可能的子串,如果指定了maxsplit,则分割会在达到maxsplit次后停止,即使字符串中还存在分隔符
  6. # 4、功能:用于将字符串分割成子字符串列表,分割基于指定的分隔符
  7. # 5、返回值:一个字符串列表,其中包含了由分隔符分隔的子字符串,即处理后的子字符串列表
  8. # 6、说明:
  9. # 6-1、如果sep不存在于字符串中,或者maxsplit设置为0或负数(且小于-1),则整个字符串将作为一个单独的子字符串返回
  10. # 7、示例:
  11. # 示例1:在空白处分割
  12. s = "Hello World"
  13. parts = s.split()
  14. print(parts) # 输出: ['Hello', 'World']
  15. # 示例2:指定分隔符
  16. s = "apple,banana,cherry"
  17. parts = s.split(",")
  18. print(parts) # 输出: ['apple', 'banana', 'cherry']
  19. # 示例3:指定分隔符和最大分割次数
  20. s = "apple,banana,cherry,date"
  21. parts = s.split(",", 2)
  22. print(parts) # 输出: ['apple', 'banana', 'cherry,date']
  23. # 示例4:如果分隔符不存在于字符串中
  24. s = "noseparatorhere"
  25. parts = s.split(",")
  26. print(parts) # 输出: ['noseparatorhere']
  27. # 示例5:指定空字符串作为分隔符
  28. s = "abc"
  29. parts = s.split("")
  30. # print(parts) # 报错:ValueError: empty separator
5-38、splitlines()方法
  1. # 1、方法:str.splitlines
  2. # 2、语法:str.splitlines([keepends])
  3. # 3、参数:
  4. # 3-1、keepends(可选):一个布尔值,指定是否在结果列表中保留行结束符(如'\n'或'\r\n');默认为False,表示不保留行结束符
  5. # 4、功能:用于将字符串按照行进行分割,返回一个包含各行作为元素的列表
  6. # 5、返回值:一个列表,其中包含了原始字符串中的各行,每行作为列表的一个元素
  7. # 6、说明:
  8. # 6-1、如果指定了keepends=True,则会在结果列表中保留行结束符
  9. # 6-2、默认情况下,不同类型的行结束符(如'\n'、'\r\n'和'\r')都会被识别并用于分割字符串,但在结果列表中不会保留这些行结束符
  10. # 7、示例:
  11. # 示例1:默认行为,不保留行结束符
  12. s = "Hello\nWorld\nHow are you?"
  13. lines = s.splitlines()
  14. print(lines) # 输出: ['Hello', 'World', 'How are you?']
  15. # 示例2:保留行结束符
  16. s = "Hello\nWorld\nHow are you?"
  17. lines = s.splitlines(keepends=True)
  18. print(lines) # 输出: ['Hello\n', 'World\n', 'How are you?']
  19. # 示例3:空字符串或只有空白字符的行也会被包含在内
  20. s = "\n\nHello\n\nWorld\n\n"
  21. lines = s.splitlines()
  22. print(lines) # 输出: ['', '', 'Hello', '', 'World', '']
  23. # 示例4:处理不同类型的行结束符
  24. s = "Hello\r\nWorld\nHow are you?\r"
  25. lines = s.splitlines()
  26. print(lines) # 输出: ['Hello', 'World', 'How are you?']
  27. # 注意:\r\n和\r都被视为行结束符,并且在结果中不保留
5-39、startswith()方法
  1. # 1、方法:str.startswith
  2. # 2、语法:str.startswith(prefix[, start[, end]])
  3. # 3、参数:
  4. # 3-1、prefix:要检查的前缀字符串
  5. # 3-2、start(可选):开始搜索的位置索引;默认为 0,表示从字符串的开始处进行搜索
  6. # 3-3、end(可选):停止搜索的位置索引(不包含该位置);默认为len(string),表示搜索到字符串的末尾
  7. # 4、功能:用于检查字符串是否以指定的前缀开始
  8. # 5、返回值:一个布尔值,表示字符串是否以指定的前缀开始
  9. # 6、说明:
  10. # 6-1、如果前缀为空字符串,则startswith()方法总是返回True,因为任何字符串都以空字符串开始
  11. # 7、示例:
  12. # 示例1:检查字符串是否以指定前缀开始
  13. s = "Hello, world!"
  14. print(s.startswith("Hello")) # 输出: True
  15. print(s.startswith("world")) # 输出: False
  16. # 示例2:指定开始搜索的位置索引
  17. s = "abcdefg"
  18. print(s.startswith("def", 3)) # 从索引3开始,因此"def"是从那里开始的,输出:True
  19. print(s.startswith("def", 4)) # 从索引4开始,因此"def"不是从那里开始的,输出:False
  20. # 示例3:指定开始和结束搜索的位置索引
  21. s = "abcdefg"
  22. print(s.startswith("cde", 2, 5)) # 从索引2开始,到索引5(不包含)结束,因此"cde"在这个范围内,输出:True
  23. print(s.startswith("cde", 2, 4)) # 从索引2开始,到索引4(不包含)结束,因此"cde"不在这个范围内,输出:False
  24. # 示例4:前缀为空字符串时总是返回True
  25. s = "Hello, world!"
  26. print(s.startswith("")) # 输出: True,因为任何字符串都以空字符串开始
5-40、strip()方法
  1. # 1、方法:str.strip
  2. # 2、语法:str.strip([chars])
  3. # 3、参数:
  4. # 3-1、chars(可选):一个字符串,指定要移除的字符集合;如果省略或为None,则移除字符串开头和结尾的所有空白字符
  5. # 4、功能:用于去除字符串开头和结尾的指定字符(默认为空白字符,包括空格、制表符、换行符等)
  6. # 5、返回值:一个新字符串,其中原始字符串开头和结尾的指定字符已被移除
  7. # 6、说明:
  8. # 7、示例:
  9. # 示例1:移除字符串开头和结尾的空白字符
  10. s = " Hello, world! "
  11. print(s.strip()) # 输出: "Hello, world!"
  12. # 示例2:移除字符串开头和结尾的指定字符
  13. s = "***Hello, world!***"
  14. print(s.strip("*")) # 输出: "Hello, world!"
  15. # 示例3:只移除字符串开头的字符
  16. s = "***Hello, world!"
  17. print(s.lstrip("*")) # 输出: "Hello, world!"
  18. # 示例4:只移除字符串结尾的字符
  19. s = "Hello, world!***"
  20. print(s.rstrip("*")) # 输出: "Hello, world!"
  21. # 示例5:移除字符串开头和结尾的多个指定字符
  22. s = "**Hello, world!!**"
  23. print(s.strip("!*")) # 输出: "Hello, world"
5-41、swapcase()方法
  1. # 1、方法:str.swapcase
  2. # 2、语法:str.swapcase()
  3. # 3、参数:无
  4. # 4、功能:用于将字符串中的所有小写字母转换为大写字母,同时将所有的大写字母转换为小写字母
  5. # 5、返回值:一个新字符串,只是原字符串中的大写字母转小写,小写字母转大写
  6. # 6、说明:
  7. # 7、示例:
  8. # 示例1:将字符串中的大小写字母互换
  9. s = "Hello, World!"
  10. swapped = s.swapcase()
  11. print(swapped) # 输出: "hELLO, wORLD!"
  12. # 示例2:包含数字和非字母字符的字符串
  13. s = "Hello123World"
  14. swapped = s.swapcase()
  15. print(swapped) # 输出: "hELLO123wORLD",数字和非字母字符保持不变
  16. # 示例3:空字符串或只包含小写字母的字符串
  17. s = ""
  18. swapped = s.swapcase()
  19. print(swapped) # 输出: "",空字符串保持不变
  20. s = "hello"
  21. swapped = s.swapcase()
  22. print(swapped) # 输出: "HELLO",所有小写字母被转换为大写字母
  23. # 示例4:只包含大写字母的字符串
  24. s = "HELLO"
  25. swapped = s.swapcase()
  26. print(swapped) # 输出: "hello",所有大写字母被转换为小写字母
5-42、title()方法
  1. # 1、方法:str.title
  2. # 2、语法:str.title()
  3. # 3、参数:无
  4. # 4、功能:用于将字符串中的每个单词的首字母转换为大写,而其余字母转换为小写
  5. # 5、返回值:一个新的字符串
  6. # 6、说明:
  7. # 7、示例:
  8. # 示例1:将字符串中的每个单词首字母转换为大写
  9. s = "hello, world!"
  10. titled = s.title()
  11. print(titled) # 输出: "Hello, World!"
  12. # 示例2:包含标点符号的字符串
  13. s = "hello-world, this is a test"
  14. titled = s.title()
  15. print(titled) # 输出: "Hello-World, This Is A Test"
  16. # 注意,标点符号后的单词也被视为独立的单词,并且其首字母也被转换为大写
  17. # 示例3:只包含小写字母的字符串
  18. s = "hello"
  19. titled = s.title()
  20. print(titled) # 输出: "Hello"
  21. # 示例4:只包含大写字母的字符串
  22. s = "HELLO"
  23. titled = s.title()
  24. print(titled) # 输出: "Hello"
  25. # 注意,尽管原始字符串全部为大写,但title()方法仍然将其视为单个单词,
  26. # 并将其转换为首字母大写,其余字母小写的形式
  27. # 示例5:包含非字母字符的字符串
  28. s = "123hello456world"
  29. titled = s.title()
  30. print(titled) # 输出: "123Hello456World"
  31. # 非字母字符前后的字母都被视为独立单词的首字母,并被转换为大写
5-43、translate()方法
  1. # 1、方法:str.translate
  2. # 2、语法:str.translate(table)
  3. # 3、参数:table是一个字典或str.maketrans()函数创建的转换表
  4. # 4、功能:用于根据一个转换表(translation table)来替换字符串中的字符
  5. # 5、返回值:一个新的字符串
  6. # 6、说明:
  7. # 6-1、translate()方法是高度优化的,通常比使用循环和条件语句来替换或删除字符要快得多
  8. # 6-2、在处理大型字符串或需要频繁进行字符替换时,使用translate()方法是一个很好的选择
  9. # 7、示例:
  10. # 示例1:使用maketrans和translate替换字符
  11. intab = "aeiou"
  12. outtab = "12345"
  13. trantab = str.maketrans(intab, outtab)
  14. str = "this is an example for translate"
  15. new_str = str.translate(trantab)
  16. print(new_str) # 输出: 'th3s 3s 1n 2x1mpl2 f2r tr1nsl173'
  17. # 示例2:删除字符串中的特定字符
  18. # 使用字典创建转换表,将需要删除的字符映射到None
  19. table = {ord(' '): None, ord(','): None, ord('.'): None}
  20. str = "hello, world. this is a test."
  21. new_str = str.translate(table)
  22. print(new_str) # 输出: 'helloworldthisisatest'
  23. # 注意:ord()函数用于获取字符的Unicode字符点(即整数值)
5-44、upper()方法
  1. # 1、方法:str.upper
  2. # 2、语法:str.upper()
  3. # 3、参数:无
  4. # 4、功能:用于将字符串中的所有小写字母转换为大写字母
  5. # 5、返回值:一个新的字符串,其中原始字符串中的小写字母已经被转换为大写,而原始字符串本身不会被修改
  6. # 6、说明:
  7. # 7、示例:
  8. # 示例1:将字符串中的小写字母转换为大写
  9. s = "hello, world!"
  10. upper_s = s.upper()
  11. print(upper_s) # 输出: "HELLO, WORLD!"
  12. # 示例2:包含数字和标点符号的字符串
  13. s = "Hello123World!"
  14. upper_s = s.upper()
  15. print(upper_s) # 输出: "HELLO123WORLD!"
  16. # 注意,数字和标点符号保持不变
  17. # 示例3:只包含大写字母的字符串
  18. s = "HELLO"
  19. upper_s = s.upper()
  20. print(upper_s) # 输出: "HELLO"
  21. # 如果字符串已经是大写,则upper()不会改变它
  22. # 示例4:空字符串
  23. s = ""
  24. upper_s = s.upper()
  25. print(upper_s) # 输出: ""
  26. # 空字符串保持不变
  27. # 示例5:包含非字母字符的字符串
  28. s = "h1e2l3l4o"
  29. upper_s = s.upper()
  30. print(upper_s) # 输出: "H1E2L3L4O"
  31. # 非字母字符保持不变
5-45、zfill()方法
  1. # 1、方法:str.zfill
  2. # 2、语法:str.zfill(width)
  3. # 3、参数:width,表示期望的字符串总长度
  4. # 4、功能:用于在字符串的左边填充零('0'),直到达到指定的总长度
  5. # 5、返回值:一个新的字符串
  6. # 6、说明:如果字符串已经足够长或超过了指定的长度,则不会进行任何更改
  7. # 7、示例:
  8. # 示例1:填充零以达到指定长度
  9. s = "42"
  10. filled_s = s.zfill(5)
  11. print(filled_s) # 输出: "00042"
  12. # 示例2:如果字符串已经足够长,则不做任何更改
  13. s = "12345"
  14. filled_s = s.zfill(4)
  15. print(filled_s) # 输出: "12345"
  16. # 示例3:填充零以用于数字字符串,如月份或日期
  17. month = "7"
  18. filled_month = month.zfill(2)
  19. print(filled_month) # 输出: "07"
  20. # 示例4:如果字符串包含非数字字符,则在左边填充零
  21. s = "abc"
  22. filled_s = s.zfill(6)
  23. print(filled_s) # 输出: "000abc"

二、推荐阅读

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

2、Python算法之旅

3、Python函数之旅

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

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

/ 登录

评论记录:

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

分类栏目

后端 (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