python string 中查找中文字符串

下面函数是从我在写的一个python自动获取天气的程序中截取的。


该函数将从中文字符串“浙江省杭州市”中,截取出"杭州"


首先将字符串编码为gbk,使用unicode(str,code),将code型编码 的 str字符串转换成unicode

然后判断字符串中是否含有"省"和"市"字,如果有就截取掉;这里注意使用  u“省”

最后返回截取的字符串


def convertName(cityName):
    '''将 “浙江省杭州市” 转换成“杭州”''' 

    name = unicode(cityName, "gbk")
    #name=cityName.encode("utf-8") #测试时,utf-8不行,未解
    print name
    
    if name.find(u"省") !=-1:# 包含'省' 
        #print u'有省'
        name=name.split(u'省')[1]
    if name.find(u"市") != -1:#包含‘市’
        #print u'有市'
        name=name.split(u'市')[0]
    return name


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用字符串的 find() 方法来查找指定字符串Python 字符串的位置。例如,如果要查找字符串 "hello" 在字符串 "hello world" 的位置,可以使用以下代码: ``` s = "hello world" index = s.find("hello") print(index) ``` 输出结果为 ,表示字符串 "hello" 在字符串 "hello world" 的起始位置为 。如果要查找字符串不存在于原字符串,则 find() 方法会返回 -1。 ### 回答2: 在Python,我们可以使用字符串的内置方法来查找指定的子字符串。 一种方式是使用`find()`方法。该方法会返回子字符串第一次出现的索引位置。如果找不到指定的子字符串,它会返回-1。例如: ```python string = "Hello, World!" index = string.find("World") print(index) # 输出:7 ``` 另一种方式是使用`index()`方法。该方法也会返回子字符串第一次出现的索引位置,但如果找不到指定的子字符串,它会抛出一个`ValueError`异常。例如: ```python string = "Hello, World!" index = string.index("World") print(index) # 输出:7 ``` 还有一种更简洁的方式是使用`in`关键字。可以直接使用`in`关键字检查子字符串是否存在于原字符串。例如: ```python string = "Hello, World!" result = "World" in string print(result) # 输出:True ``` 以上是一些常用的方法来在Python字符串查找指定的子字符串。根据具体的需求可以选择使用适合的方法。 ### 回答3: 在Python,我们可以使用`index()`和`find()`这两个方法来查找指定字符串字符串的位置。 `index()`方法返回指定字符串字符串首次出现的位置,如果指定字符串不存在,则会抛出ValueError异常。例如,我们有一个字符串s = "Hello, world!",我们可以使用`s.index("world")`来查找"world"在s的位置。如果"world"存在于s,则返回值为6。 `find()`方法与`index()`类似,它也返回指定字符串字符串首次出现的位置。但是,如果指定字符串不存在,则返回-1而不会抛出异常。所以,如果我们使用`s.find("world")`来查找"world"在s的位置,如果"world"存在于s,则返回值为6;如果"world"不存在于s,则返回值为-1。 下面是一个实例代码,演示了如何在Python字符串查找指定字符串: ```python s = "Hello, world!" target = "world" # 使用index()方法查找指定字符串 try: index = s.index(target) print(f"{target}在{s}的位置为:{index}") except ValueError: print(f"{target}在{s}不存在") # 使用find()方法查找指定字符串 index = s.find(target) if index >= 0: print(f"{target}在{s}的位置为:{index}") else: print(f"{target}在{s}不存在") ``` 输出结果为: ``` world在Hello, world!的位置为:7 world在Hello, world!的位置为:7 ``` 这样,我们就可以使用`index()`和`find()`方法来在Python字符串查找指定字符串了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值