【问题标题】:how do find and replace string with python如何用python查找和替换字符串
【发布时间】:2016-07-08 07:00:33
【问题描述】:

有这样的字符串

100Usable by Everybody: Design Principles for Accessibility on Mac OS X 101What's New in Cocoa Touch 102What's New in Foundation for iOS 4 103iPad and iPhone User Interface Design 104Designing Apps with Scroll Views 308Developing Your App with Xcode 4 309Advanced Performance Analysis with Instruments 419OpenGL ES Tuning and Optimization 420OpenGL for Mac OS X 421Incorporating the Camera and Photo Library in your App 422Taking Advantage of Multiple GPUs

我想找到所有的数字子串,所以我得到了一组数字字符串,其中一个会像'100'。然后我修改它,在它前面附加'\n-'。所以最后我会得到一个这样的字符串

- 100 Usable by Everybody: Design Principles for Accessibility on Mac OS X 
- 101 What's New in Cocoa Touch 
- 102 What's New in Foundation for iOS 4 
- 103 iPad and iPhone User Interface Design 
- 104 Designing Apps with Scroll Views
- 308 Developing Your App with Xcode 4 
- 309 Advanced Performance Analysis with Instruments 
- 419 OpenGL ES Tuning and Optimization 
- 420 OpenGL for Mac OS X 
- 421 Incorporating the Camera and Photo Library in your App 
- 422 Taking Advantage of Multiple GPUs

我怎样才能用python做到这一点,请帮忙。非常感谢。


找到数字子串后,我使用它。例如,我找到'100',然后将其替换为'\n - 100'。

【问题讨论】:

  • 这里的逻辑是什么,为什么不在iOS 4处添加换行符? 4 也是一个数字。
  • 标记总是3位数吗?
  • @cdarke 是的!我该怎么做?

标签: python


【解决方案1】:

假设数字始终为 3 位数字(因为您在数据中嵌入了其他数字):

data = "100Usable by Everybody: Design Principles for Accessibility on Mac OS X 101What's New in Cocoa Touch 102What's New in Foundation for iOS 4 103iPad and iPhone User Interface Design 104Designing Apps with Scroll Views 105Adopting Multitasking on iPhone OS, Part 1 106Understanding Document Interaction Controller 107Cocoa Tips and Tricks"

import re

new_data = re.sub(r'(\d{3})', '\n- \\1 ', data)
print(new_data)

给予:

- 100 Usable by Everybody: Design Principles for Accessibility on Mac OS X 
- 101 What's New in Cocoa Touch 
- 102 What's New in Foundation for iOS 4 
- 103 iPad and iPhone User Interface Design 
- 104 Designing Apps with Scroll Views 
- 105 Adopting Multitasking on iPhone OS, Part 1 
- 106 Understanding Document Interaction Controller 
- 107 Cocoa Tips and Tricks

【讨论】:

  • 很好的解决方案。非常感谢。
  • 好的,一个警告:你必须保证文本数据在任何地方都不包含3位数字!
  • 文本数据始终包含 3 位数字。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多