首页 最新 热门 推荐

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

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

  • 25-03-03 04:22
  • 3427
  • 8893
blog.csdn.net

目录

一、字符串

1、字符串的定义

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

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

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

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

2、字符串的语法

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

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

5、字符串的用法

5-1、capitalize()方法

5-2、casefold()方法

5-3、center()方法

5-4、count()方法

5-5、encode()方法

5-6、endswith()方法 

5-7、expandtabs()方法

5-8、find()方法

5-9、format()方法

5-10、format_map()方法

5-11、index()方法

5-12、isalnum()方法

5-13、isalpha()方法

5-14、isascii()方法

5-15、isdigit()方法

二、推荐阅读

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-1、capitalize()方法
  1. # capitalize()方法:将字符串的第一个字符转换为大写,其余字符转换为小写,且不影响原始字符串
  2. s = "hello, my Pyton World!"
  3. s_capitalized = s.capitalize()
  4. print(s_capitalized) # 输出: Hello, my pyton world!
  5. print(s) # 输出: hello, my Pyton World!
5-2、casefold()方法
  1. # casefold()方法:将字符串中的所有字符转换为小写,并进行额外的折叠映射,以考虑不同语言环境的“大小写不敏感”比较,这与lower()方法有些相似,
  2. # 但casefold()提供了更彻底的折叠,使得字符串在比较时更加“平等”
  3. # 该方法不影响原始字符串
  4. s = "Hello, my Python World!"
  5. s_casefolded = s.casefold()
  6. print(s_casefolded) # 输出:hello, my python world!
  7. print(s) # 输出: Hello, my Python World!
5-3、center()方法
  1. # 1、方法:str.center
  2. # 2、语法:str.center(width[, fillchar])
  3. # 3、参数:
  4. # 3-1、width(必需):整数,表示新字符串的总宽度
  5. # 3-2、fillchar(可选):单个字符,用于填充新字符串的空白部分,默认为空格
  6. # 4、功能:将字符串居中,并在其两侧填充指定的字符(默认为空格)
  7. # 5、返回值:一个新的字符串
  8. # 6、说明:
  9. # 6-1、如果原始字符串的长度大于或等于width,则center()方法会返回原始字符串的副本
  10. # 6-2、此方法不影响原始字符串
  11. # 7、示例:
  12. # 原始字符串
  13. s = "myelsa"
  14. # 使用center方法,总宽度为10,默认填充字符为空格
  15. s_centered = s.center(10)
  16. print(s_centered) # 输出:' myelsa '
  17. # 使用center方法,总宽度为10,指定填充字符为'*'
  18. s_centered_with_star = s.center(10, '*')
  19. print(s_centered_with_star) # 输出: '**myelsa**'
  20. # 注意原始字符串s并没有改变
  21. print(s) # 输出: 'myelsa'
5-4、count()方法
  1. # 1、方法:str.count
  2. # 2、语法:str.count(sub[, start[, end]])
  3. # 3、参数:
  4. # 3-1、sub:要搜索的子字符串
  5. # 3-2、start(可选):开始搜索的索引位置;默认为0,即字符串的开始
  6. # 3-3、end(可选):结束搜索的索引位置(不包括该位置);默认为字符串的末尾
  7. # 4、功能:用于计算子字符串在字符串中出现的次数
  8. # 5、返回值:一个非负整数
  9. # 6、说明:
  10. # 6-1、如果子字符串在字符串中不存在,则返回0
  11. # 6-2、当使用start和end参数时,count()方法只会计算在指定范围内子字符串出现的次数(遵守左闭右开原则)
  12. # 7、示例:
  13. # 原始字符串
  14. s = "hello world, hello everyone"
  15. # 计算子字符串 "hello" 出现的次数
  16. count_hello = s.count("hello")
  17. # 输出结果
  18. print(count_hello) # 输出: 2
  19. # 计算子字符串 "world" 出现的次数
  20. count_world = s.count("world")
  21. # 输出结果
  22. print(count_world) # 输出: 1
  23. # 计算子字符串 "python" 出现的次数(不存在)
  24. count_python = s.count("python")
  25. # 输出结果
  26. print(count_python) # 输出: 0
  27. # 使用start和end参数
  28. count_hello_start_end = s.count("hello", 7, 20) # 只搜索索引7到20之间的部分(不包括20)
  29. # 输出结果
  30. print(count_hello_start_end) # 输出: 1,因为第二个 "hello" 在这个范围内
5-5、encode()方法
  1. # 1、方法:str.encode
  2. # 2、语法:str.encode(encoding='utf-8', errors='strict')
  3. # 3、参数:
  4. # 3-1、encoding:指定字符编码的名称,默认为'utf-8';Python支持多种字符编码,但最常用的是'utf-8',它能够表示任何Unicode字符
  5. # 3-2、errors:指定如何处理编码错误。默认是'strict',表示如果无法编码某个字符,则抛出UnicodeEncodeError;
  6. # 其他可能的值包括'ignore'(忽略无法编码的字符)、'replace'(用问号?替换无法编码的字符)和'xmlcharrefreplace'(使用XML字符引用替换无法编码的字符)
  7. # 4、功能:用于将字符串转换为字节串(bytes)
  8. # 5、返回值:一个字节串(bytes)
  9. # 6、说明:
  10. # 7、示例:
  11. # 原始字符串
  12. s = "Hello, World!"
  13. # 编码为UTF-8字节串
  14. b_utf8 = s.encode('utf-8')
  15. # 打印字节串
  16. print(b_utf8) # 输出: b'Hello, World!'
  17. # 尝试使用不支持的编码
  18. try:
  19. b_latin1 = s.encode('latin1') # 如果字符串中只包含Latin-1字符,这将成功
  20. print(b_latin1) # 输出:b'Hello, World!'
  21. except UnicodeEncodeError as e:
  22. print(f"编码错误: {e}")
  23. # 使用'replace'处理编码错误
  24. s_with_non_ascii = "Hello, 世界!"
  25. b_with_replacement = s_with_non_ascii.encode('ascii', 'replace')
  26. # 打印带有替换字符的字节串
  27. print(b_with_replacement) # 输出: b'Hello, ??!'
5-6、endswith()方法 
  1. # 1、方法:str.endswith
  2. # 2、语法:str.endswith(suffix[, start[, end]])
  3. # 3、参数:
  4. # 3-1、suffix(必须):表示要检查的后缀
  5. # 3-2、start(可选):指定开始检查的起始位置(索引);默认为0,即字符串的开始
  6. # 3-3、end(可选):指定结束检查的结束位置(索引);默认为字符串的长度,即字符串的末尾
  7. # 4、功能:用于检查字符串是否以指定的后缀结束
  8. # 5、返回值:一个布尔值
  9. # 6、说明:如果字符串以指定的后缀结束,则返回 True,否则返回 False
  10. # 7、示例:
  11. # 原始字符串
  12. s = "Hello, World!"
  13. # 检查字符串是否以"World!"结尾
  14. is_endswith_world = s.endswith("World!")
  15. print(is_endswith_world) # 输出: True
  16. # 检查字符串是否以"Hello"结尾(不是)
  17. is_endswith_hello = s.endswith("Hello")
  18. print(is_endswith_hello) # 输出: False
  19. # 检查字符串从索引5开始到结束是否以"World!"结尾(是)
  20. is_endswith_world_from_index5 = s.endswith("World!", 7) # 注意:索引7是"W"的位置,但不影响结果
  21. print(is_endswith_world_from_index5) # 输出: True
  22. # 检查字符串从索引0开始到索引10是否以"ello"结尾(不是)
  23. is_endswith_ello = s.endswith("ello", 0, 11) # 注意:索引11超出了字符串长度,但不影响检查到索引10的部分
  24. print(is_endswith_ello) # 输出: False
5-7、expandtabs()方法
  1. # 1、方法:str.expandtabs
  2. # 2、语法:str.expandtabs([tabsize=8])
  3. # 3、参数:
  4. # 3-1、tabsize(可选):表示一个制表符应该由多少个空格代替;默认值是8,这通常是大多数系统中制表符的标准宽度
  5. # 4、功能:用于将字符串中的制表符(\t)替换为一定数量的空格,从而扩展它们以匹配指定的制表符宽度
  6. # 5、返回值:返回一个新的字符串
  7. # 6、说明:expandtabs()方法返回一个新的字符串,而原始字符串保持不变
  8. # 7、示例:
  9. # 使用默认的制表符宽度(8个空格)
  10. s = "Hello\tWorld"
  11. expanded_s = s.expandtabs()
  12. print(expanded_s) # 输出: Hello World
  13. # 使用自定义的制表符宽度(4个空格)
  14. s = "Hello\tWorld"
  15. expanded_s = s.expandtabs(tabsize=11)
  16. print(expanded_s) # 输出: Hello World
  17. # 字符串中有多个制表符
  18. s = "Hello\t\tWorld"
  19. expanded_s = s.expandtabs()
  20. print(expanded_s) # 输出: Hello World
5-8、find()方法
  1. # 1、方法:str.find
  2. # 2、语法:str.find(sub[, start[, end]])
  3. # 3、参数:
  4. # 3-1、sub(必需):表示要查找的子字符串
  5. # 3-2、start(可选):表示开始查找的位置索引;默认值为0,表示从字符串的开始位置查找
  6. # 3-3、end(可选):表示结束查找的位置索引;默认值为字符串的长度,表示查找到字符串的末尾
  7. # 4、功能:用于查找子字符串在主字符串中首次出现的位置索引
  8. # 5、返回值:返回子字符串在主字符串中首次出现的位置索引
  9. # 6、说明:
  10. # 6-1、当指定了起始索引时,find()方法将从该索引开始查找
  11. # 6-2、如果未找到子字符串,或者起始索引大于结束索引,则find()方法返回-1
  12. # 7、示例:
  13. # 查找子字符串首次出现的位置
  14. s = "Hello, World!"
  15. index = s.find("World")
  16. print(index) # 输出: 7
  17. # 查找子字符串首次出现的位置(指定起始索引)
  18. index = s.find("World", 6) # 从索引6开始查找
  19. print(index) # 输出: 7
  20. # 查找不存在的子字符串
  21. index = s.find("Python")
  22. print(index) # 输出: -1
  23. # 查找子字符串在指定范围内的位置
  24. index = s.find("o", 1, 5) # 从索引1开始到索引5结束(不包括索引5)查找'o'
  25. print(index) # 输出: 4
  26. # 如果起始索引大于结束索引,find()会返回 -1
  27. index = s.find("o", 10, 5)
  28. print(index) # 输出: -1
5-9、format()方法
  1. # 在Python中,字符串的format()方法提供了一种灵活的方式来格式化字符串
  2. # format()方法可以与字符串字面量中的大括号`{}`占位符一起使用,或者与`str.format()`方法一起使用来插入和格式化变量值
  3. # 1、基本用法
  4. # 使用`{}`占位符,并在调用`format()`方法时提供参数:
  5. name = "Myelsa"
  6. age = 18
  7. formatted_string = "My name is {} and I am {} years old.".format(name, age)
  8. print(formatted_string) # 输出: My name is Myelsa and I am 18 years old.
  9. # 2、命名参数
  10. # 在`{}`中使用变量名来引用参数:
  11. name = "Bruce"
  12. formatted_string = "Hello, {name}!".format(name=name)
  13. print(formatted_string) # 输出: Hello, Bruce!
  14. # 3、位置参数
  15. # 使用位置参数,与占位符的顺序对应:
  16. name = "Jimmy"
  17. age = 15
  18. formatted_string = "Name: {}, Age: {}".format(name, age)
  19. print(formatted_string) # 输出: Name: Jimmy, Age: 15
  20. # 4、格式化数字
  21. # 使用冒号`:`后的格式说明符来格式化数字:
  22. pi = 3.141592653589793
  23. formatted_string = "Pi is approximately {:.4f}".format(pi)
  24. print(formatted_string) # 输出: Pi is approximately 3.1416
  25. # 5、格式说明符
  26. # 5-1、`{}`:占位符
  27. # 5-2、`:`:开始格式说明符
  28. # 5-3、`.`(可选):用于指定小数点后的精度
  29. # 5-4、`<`, `>`, `^`(可选):用于指定对齐方式(左对齐、右对齐、居中对齐)
  30. # 5-5、`+`(可选):用于在数字前显示正负号
  31. # 5-6、`-`(可选):用于左对齐(默认是右对齐)
  32. # 5-7、空格(可选):在正数前加一个空格
  33. # 5-8、`#`(可选):用于二进制、八进制、十六进制表示,以及浮点数的小数点和指数
  34. # 5-9、`0`(可选):用于指定填充的字符(如果指定了宽度)
  35. # 5-10、数字(可选):指定最小宽度
  36. # 5-11类型(可选):如`f`(浮点数)、`s`(字符串)、`d`(整数)等
  37. # 6、嵌套和复杂用法
  38. # `format()`方法还支持更复杂的嵌套和格式化,例如访问列表、字典或对象的属性:
  39. person = {"name": "Jimmy", "age": 15, "city": "Foshan"}
  40. formatted_string = "My name is {name}, I am {age} years old, and I live in {city}.".format(**person)
  41. print(formatted_string) # 输出: My name is Jimmy, I am 15 years old, and I live in Foshan.
  42. # 7、访问列表中的元素
  43. items = ["apple", "banana", "cherry"]
  44. formatted_string = "I have {} items: {}".format(len(items), ", ".join(items))
  45. print(formatted_string) # 输出: I have 3 items: apple, banana, cherry
  46. # 8、f-string(Python 3.6+)
  47. # 从Python 3.6开始,可以使用f-string(格式化字符串字面量)作为另一种更简洁、易读的字符串格式化方法:
  48. name = "Myelsa"
  49. age = 18
  50. formatted_string = f"My name is {name} and I am {age} years old."
  51. print(formatted_string) # 输出: My name is Myelsa and I am 18 years old.
  52. # f-string允许在字符串中直接嵌入表达式,并在运行时求值,这使得字符串格式化更加简洁和直观
5-10、format_map()方法
  1. # 1、方法:str.format_map
  2. # 2、语法:str.format_map(mapping)
  3. # 3、参数:
  4. # 3-1、mapping(必需):表示映射类型,如字典等
  5. # 4、功能:接受一个映射类型作为参数,并使用映射类型中的键值对来替换字符串中的格式化字段
  6. # 5、返回值:一个新的字符串
  7. # 6、说明:注意,format_map()方法只能处理字典或其他映射类型中的键值对,与 str.format()方法相比,它提供了一种更简洁、更直观的方式来使用字典进行字符串格式化
  8. # 7、示例:
  9. # 定义一个包含要格式化的数据的字典
  10. data = {
  11. 'name': 'Myelsa',
  12. 'age': 18,
  13. 'city': 'Guangzhou'
  14. }
  15. # 定义一个带有格式化字段的字符串模板
  16. template = 'My name is {name}, I am {age} years old, and I live in {city}.'
  17. # 使用format_map()方法来格式化字符串
  18. formatted_string = template.format_map(data)
  19. # 输出格式化后的字符串
  20. print(formatted_string) # 输出:My name is Myelsa, I am 18 years old, and I live in Guangzhou.
5-11、index()方法
  1. # 1、方法:str.index
  2. # 2、语法:str.index(sub[, start[, end]])
  3. # 3、参数:
  4. # 3-1、sub(必需):表示要查找的子字符串
  5. # 3-2、start(可选):表示开始查找的位置索引;默认值为0,表示从字符串的开始位置查找
  6. # 3-3、end(可选):表示结束查找的位置索引;默认值为字符串的长度,表示查找到字符串的末尾
  7. # 4、功能:用于查找子字符串在主字符串中首次出现的位置索引
  8. # 5、返回值:一个正整数
  9. # 6、说明:
  10. # 6-1、如果start参数大于end参数,或者sub参数在主字符串中不存在,index()方法会抛出一个ValueError异常;因此,在使用index()方法时,最好使用try-except块来捕获并处理可能的异常
  11. # 6-2、与find()方法不同,index()方法在找不到子字符串时会抛出ValueError异常,而find()方法会返回-1
  12. # 7、示例:
  13. s = "Hello, World!"
  14. # 查找子字符串首次出现的位置
  15. index = s.index("World")
  16. print(index) # 输出: 7
  17. # 查找子字符串首次出现的位置(指定起始索引)
  18. index = s.index("World", 8) # 注意:这里会抛出ValueError,因为从索引8开始找不到"world"
  19. # print(index) # 这行代码会抛出 ValueError: substring not found
  20. # 查找不存在的子字符串
  21. try:
  22. index = s.index("Python")
  23. print(index)
  24. except ValueError:
  25. print("Substring not found") # 输出: Substring not found
  26. # 查找子字符串在指定范围内的位置
  27. index = s.index("o", 1, 5) # 从索引1开始到索引5结束(不包括索引5)查找'o'
  28. print(index) # 输出: 4
5-12、isalnum()方法
  1. # 1、方法:str.isalnum
  2. # 2、语法:str.isalnum()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串中的所有字符是否都是字母(alphabetic)或数字(numeric),并且字符串至少包含一个字符
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、如果字符串中所有字符都是字母或数字,则返回True,否则返回False
  8. # 6-2、isalnum()方法只会检查字符串中的字符是否是字母或数字,而不会考虑字符的大小写(即大写字母和小写字母都被视为字母)
  9. # 6-3、该方法也不会考虑字符串中的空白字符(如空格、制表符、换行符等),因此即使字符串中包含一个空格,isalnum()也会返回False
  10. # 6-4、如果参数为空,isalnum()会返回False
  11. # 7、示例:
  12. s1 = "Hello 123"
  13. print(s1.isalnum()) # 输出: False,因为包含非字母非数字的字符(空格)
  14. s2 = "Hello 123"
  15. print(s2.replace(" ", "").isalnum()) # 输出: True,移除空格后,所有字符都是字母或数字
  16. s3 = "12345"
  17. print(s3.isalnum()) # 输出: True,所有字符都是数字
  18. s4 = "abcdef"
  19. print(s4.isalnum()) # 输出: True,所有字符都是字母
  20. s5 = "Hello World"
  21. print(s5.isalnum()) # 输出: False,包含空格
  22. s6 = "Hello123!"
  23. print(s6.isalnum()) # 输出: False,包含非字母非数字的字符(感叹号)
  24. s7 = ""
  25. print(s7.isalnum()) # 输出: False,空字符串
5-13、isalpha()方法
  1. # 1、方法:str.isalpha
  2. # 2、语法:str.isalpha()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串中的所有字符是否都是字母,并且至少包含一个字符
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、如果字符串中所有字符都是字母,则返回True,否则返回False
  8. # 6-2、isalpha()方法只考虑字母字符,包括大写和小写字母,它不会考虑数字、空白字符(如空格、制表符、换行符等)或其他特殊字符
  9. # 6-3、如果参数为空,isalpha()会返回False
  10. # 7、示例:
  11. s1 = "Hello"
  12. print(s1.isalpha()) # 输出: True,因为所有字符都是字母
  13. s2 = "Hello123"
  14. print(s2.isalpha()) # 输出: False,因为包含数字
  15. s3 = "Hello World"
  16. print(s3.isalpha()) # 输出: False,因为包含空格
  17. s4 = "Hello!"
  18. print(s4.isalpha()) # 输出: False,因为包含非字母字符(感叹号)
  19. s5 = ""
  20. print(s5.isalpha()) # 输出: False,空字符串
  21. s6 = "12345"
  22. print(s6.isalpha()) # 输出: False,所有字符都是数字
  23. s7 = "Helloもじ"
  24. print(s7.isalpha()) # 输出: True 因为所有字符都是字母,即使字母是用日文表示
5-14、isascii()方法
  1. # 1、方法:str.isdecimal
  2. # 2、语法:str.isdecimal()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串中的所有字符是否都是十进制数字,且至少有一个这样的字符
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、如果字符串中的所有字符都是十进制数字则返回True,否则返回False
  8. # 6-2、isdecimal()方法只检查字符串中的字符是否属于Unicode十进制数字类别,它不会识别像罗马数字、中文数字或其他非标准的数字表示形式
  9. # 6-3、如果你需要更广泛的数字检测(包括小数点、负号等),你可能需要使用正则表达式或其他字符串处理方法
  10. # 7、示例:
  11. s1 = "12345"
  12. print(s1.isdecimal()) # 输出: True,因为所有字符都是十进制数字
  13. s2 = "12345a"
  14. print(s2.isdecimal()) # 输出: False,因为包含非数字字符
  15. s3 = "123.45"
  16. print(s3.isdecimal()) # 输出: False,因为包含小数点
  17. s4 = ""
  18. print(s4.isdecimal()) # 输出: False,空字符串不包含任何十进制数字字符
  19. s5 = "⅛" #(这里使用的是分数形式的数字)
  20. print(s5.isdecimal()) # 输出: False,因为包含非十进制数字字符
5-15、isdigit()方法
  1. # 1、方法:str.isdigit
  2. # 2、语法:str.isdigit()
  3. # 3、参数:无
  4. # 4、功能:用于检查字符串中的所有字符是否都是数字字符,且至少有一个这样的字符
  5. # 5、返回值:一个布尔值
  6. # 6、说明:
  7. # 6-1、如果字符串中的所有字符都是数字字符则返回 True,否则返回 False
  8. # 6-2、isdigit() 方法只检查字符串中的字符是否属于标准的数字字符(即0-9),它不会识别像罗马数字、中文数字或其他非标准的数字表示形式
  9. # 6-3、如果你需要更广泛的数字检测(包括小数点、负号等),你可能需要使用正则表达式或其他字符串处理方法
  10. # 7、示例:
  11. s1 = "12345"
  12. print(s1.isdigit()) # 输出: True,因为所有字符都是数字字符
  13. s2 = "12345a"
  14. print(s2.isdigit()) # 输出: False,因为包含非数字字符
  15. s3 = "123.45"
  16. print(s3.isdigit()) # 输出: False,因为包含小数点
  17. s4 = ""
  18. print(s4.isdigit()) # 输出: False,空字符串不包含任何数字字符
  19. s5 = "⅛" #(这里使用的是分数形式的数字)
  20. print(s5.isdigit()) # 输出: False,因为包含非数字字符

二、推荐阅读

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

2、Python算法之旅

3、Python函数之旅

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

注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/139009173"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

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

分类栏目

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