python - 根据 STR 中的条件插入 ',' - Python

标签 python list conditional-statements

我正在处理一长串看起来像这样的街道名称:

1820 W 9000 SWest Jordan
455 S 500 ESalt Lake City
555 S 200 WBountiful
1000 N Green Valley PkwyHenderson
10100 W Tropicana AveLas Vegas
10305 S 1300 ESandy
10600 Southern Highlands PkwyLas Vegas
10616 S Eastern AveHenderson
111 Coors Blvd NWAlbuquerque
1170 E Gentile StLayton
1174 W 600 NSalt Lake City
1200 W Main StRiverton
....
....

我试图在城市名称之前插入一个“,”,它总是出现在一个小写字符之后,后跟一个无空格和一个大写字符。

所以这是我的想法:

我如何写出或多或少的内容:

for cities in lst:
    if [char] is lower and [nextchar] is UPPER:
        [insert] ',' before UPPER

最佳答案

按照@Martijn 的建议,采用组中的最后一个大写字母,也许:

import re
def fix(s):
    return re.sub("([a-z]|[A-Z]+)([A-Z])",r"\1,\2", s)

给出

>>> for line in lines:
...     print fix(line)
...     
1820 W 9000 S,West Jordan
455 S 500 E,Salt Lake City
555 S 200 W,Bountiful
1000 N Green Valley Pkwy,Henderson
10100 W Tropicana Ave,Las Vegas
10305 S 1300 E,Sandy
10600 Southern Highlands Pkwy,Las Vegas
10616 S Eastern Ave,Henderson
111 Coors Blvd NW,Albuquerque
1170 E Gentile St,Layton
1174 W 600 N,Salt Lake City
1200 W Main St,Riverton

[免责声明:我对正则表达式很糟糕。]

关于python - 根据 STR 中的条件插入 ',' - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20081096/

相关文章:

javascript - "else if"Javascript计算器中的条件

python - 使用 autbahn.asyncio.wamp 非阻塞地运行多个 ApplicationSession

python - 如何编写一个用 @defer.inlineCallbacks 装饰的方法,该方法可能会产生也可能不会产生?

Python:从http到csv

android - 获取应用开发者姓名

sql-server - 用于保存整数列表的 SQL 变量

python - 如何删除列表中的所有奇数项?

具有混合条件的 bash while 循环

python - 在 Mac OS X 上使用 pip 安装 pycrypto 时出现 Broken Pipe 错误

Javascript 文本更改不起作用