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/

相关文章:

python - 当绘图到达 QChartView 边框时如何 ScrollView

python - gevent 和 SSL 导致 "EOF occurred in violation of protocol"

python - 如何在 Python 中处理 AssertionError 并找出它发生在哪一行或哪条语句上?

python - 如何将一维数组转换为逻辑矩阵

Java:无限while循环中的If语句

Java : Creating chunks of List for processing

c# - 如何将 List 的多个值放入 M​​essageBox

python - 如何压缩两个不同大小的列表?

python - 有条件地返回函数的最pythonic方法是什么

.net:硬编码条件还是什么?