【问题标题】:How to manipulate text in the middle of a string?如何操作字符串中间的文本?
【发布时间】:2018-10-06 14:19:59
【问题描述】:

如何使用 Python 在特定索引处连接字符串中的单词?
例如:- 在字符串中,

"Delhi is the capital of India." 

我需要在“the”之前和之后连接'123'

输出应该是:-"Delhi is 123the123 capital of India."

【问题讨论】:

  • 那是插入,不是串联。
  • str.replace(' the ', ' 123the123 ').
  • 这不是真正的串联,它更像是字符串操作。正如@Austin 建议的那样,您可以使用str.replace() 简单地替换字符串中的。我们也不知道您计划使用它的范围。如果您有多个重复出现“the”一词的不同字符串,那么这个特定示例将不适合您。请进一步说明您打算如何使用它。
  • 字符串在 python 中是不可变的,你只能创建新的字符串,f.e.通过使用replace 等字符串方法或通过切片 - 请参阅slice strings
  • 感谢大家提供的所有信息。

标签: python string primitive


【解决方案1】:

您可以使用str.replace().split()enumerate() 来完成此操作

使用 str.replace()

s = "Delhi is the capital of India." 
s = s.replace('the', '123the123')
# Delhi is 123the123 capital of India.

使用 .split()enumerate()

s = "Delhi is the capital of India." 
s = s.split()
for i, v in enumerate(s):
    if v == 'the':
        s[i] = '123the123'
s = ' '.join(s)

' '.join() 带有 生成器表达式

print(' '.join("123the123" if w=="the" else w for w in s.split()))

进一步阅读

https://docs.python.org/3/library/stdtypes.html#string-methods https://en.m.wikipedia.org/wiki/Scunthorpe_problem

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2011-12-16
  • 1970-01-01
相关资源
最近更新 更多