python - 如何在Python中指定不同的第一个单词

标签 python string line

我有一个 txt 文件,其中包含以下几行:

місто Ясинуватського р-ну Донецької обл.#1#Авдіївка
м., ліва притока Інгул.#3#Аджамка (Аджимка, Аджинка

我已经做到了这一点(Python 2.7):

for line in text.splitlines():
  if line.startswith(u'місто'):       
    before_keyword, after_keyword = line.rsplit(u'#',1)
    encoded=after_keyword.encode('cp1251')
    print encoded

如何指定我的行应u"місто"u"м."* 开头? 我希望我的结果是:

Авдіївка

Аджамка (Аджимка, Аджинка

最佳答案

您可以将值元组传递给str.startswith:

if line.startswith((u'місто', u'м.')):

关于str.startswith的帮助:

startswith(...)
    S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

关于python - 如何在Python中指定不同的第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19924988/

相关文章:

Python Pandas 从 Groupby 中选择组的随机样本

python - 无法在 SUSE 上安装 python-pip

c++ - 使用 OpenCV 在交叉点画线

python-2.7 - 在 OpenCV 中画一条线不起作用

python - 检查数组数组中数组是否存在 python

python - 使用 .txt 文件作为字典

Java字符串对象的创建

ruby-on-rails - 如果字符串包含 ruby​​ 命令,如何评估 ruby​​ 中的字符串?

c - 字符串旋转

ruby - 使用正则表达式对散列进行行拆分