玖叶教程网

前端编程开发入门

Python 字符串替换(python字符串替换对应字母)

Python 字符串替换

4 分钟阅读

在 Python 中替换字符串的一种简单而强大的方法是使用 Python 字符串 replace() 方法。

Python 是最好的脚本语言之一,它最容易与 Selenium Webdriver 集成以实现基于 Web 的自动化,这需要大量的字符串处理。可能需要使用字符串处理来构建动态 XPath、比较日期和搜索子字符串。因此使用 Python 字符串 replace() 方法是不可避免的。

在 Python 中替换字符串

  • 如何在 Python 中替换字符串
  • Python replace() 方法签名
  • Python 中的字符串替换示例


用示例定义 Python 字符串替换方法

如何在 Python 中替换字符串

通常,您将在 Python 中处理字符串,通过用另一部分文本替换一部分来修改其内容。(str object)

在Python中一切都是一个对象,对于字符串也是如此。这意味着这是一个字符串对象。Python 的字符串模块提供了一个 replace() 方法

1-调用 replace()

Python replace() 方法签名

<string.replace()> 方法具有以下语法。

str.replace(s, old, new[, replacefreq])

下面是传递给该方法的参数的摘要。

参数

描述

<>

它是要从中搜索和替换的字符串的值。

<old>

旧子字符串的值。

<new>

替换为新子字符串的值。

<replacefreq>

它表示字符串将被替换的次数。

Python 中的字符串替换示例


示例 1:使用模块名称调用 replace()

oldString = 'I love Python 2.0'

import string
 
newString = string.replace(oldString, '2.0', '3.0')
print(newString)
 
newString = string.replace(oldString, '2.0', '3.0.')
print(newString)
 
oldString = 'Are you a tester who tests websites? Be a good tester.'
newString = string.replace(oldString, 'test', 'develop', 1)
print(newString)

newString = string.replace(oldString, 'test', 'develop', 2)
print(newString)

newString = string.replace(oldString, 'test', 'develop', 3)
print(newString)

代码将产生以下输出。

I love Python 3.0
I love Python 3.0.
Are you a developer who tests websites? Be a good tester.
Are you a developer who develops websites? Be a good tester.
Are you a developer who develops websites? Be a good developer.

示例 2:使用 <str> 对象调用 replace()

oldString = 'I love Python 2.0'
 
newString = oldString.replace('2.0', '3.0')
print(newString)
 
newString = oldString.replace('2.0', '3.0.')
print(newString)
 
oldString = 'Are you a tester who tests websites? Be a good tester.'
newString = oldString.replace('test', 'develop', 1)
print(newString)

newString = oldString.replace('test', 'develop', 2)
print(newString)

newString = oldString.replace('test', 'develop', 3)
print(newString)

在这里,它是上面 Python 字符串 replace() 示例的输出。

I love Python 3.0
I love Python 3.0.
Are you a developer who tests websites? Be a good tester.
Are you a developer who develops websites? Be a good tester.
Are you a developer who develops websites? Be a good developer.

总结

Python 中使用字符串对象的 replace() 方法或者使用string模块

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言