简体   繁体   English

遍历字符串,仅返回某些字符。 蟒蛇

[英]Looping through a string and only returning certain characters. Python

I have a problem when creating a function that's supposed to first return lowercase letters, "_" and "." 创建应该首先返回小写字母“ _”和“”的函数时遇到问题。 and then uppercase letters, " " and "|" 然后是大写字母“”和“ |” in that order. 以该顺序。 My version seems to return numbers and special characters like <>@ too which I don't want it to do, It's only supposed to read through the input string once and I don't know if that's achieved with my code. 我的版本似乎也返回数字和特殊字符,例如<> @,但我也不希望这样做,它只能读取一次输入字符串,而且我不知道这是用我的代码实现的。

My code is: 我的代码是:

def split_iterative(n):
    splitted_first = ""
    splitted_second = ""
    for i in n:
        if i == i.lower() or i == "_" or i == ".":
            splitted_first = splitted_first + i
        elif i == i.upper() or i == " " or i == "|":
            splitted_second = splitted_second + i
    return splitted_first + splitted_second

if I do s plit_iterative("'lMiED)teD5E,_hLAe;Nm,0@Dli&Eg ,#4aI?rN@T§&e7#4E #<(S0A?<)NT8<0'")) it returns "'li)te5,_he;m,0@li&g ,#4a?r@§&e7#4 #<(0?<)8<0'MEDDELANDEINTESANT" which is incorrect as it should eliminate all those special characters and numbers. 如果我执行plit_iterative("'lMiED)teD5E,_hLAe;Nm,0@Dli&Eg ,#4aI?rN@T§&e7#4E #<(S0A?<)NT8<0'"))则返回"'li)te5,_he;m,0@li&g ,#4a?r@§&e7#4 #<(0?<)8<0'MEDDELANDEINTESANT" ,这是错误的,因为它应该消除所有这些特殊字符和数字。 How do I fix this? 我该如何解决? It should return ('lite_hemligare', 'MEDDELANDE INTE SANT') 它应该返回('lite_hemligare', 'MEDDELANDE INTE SANT')

You could try this: 您可以尝试以下方法:

def f(input_string):
    str1 = str2 = ""
    for character in input_string:
        if character.isalpha():
            if character.islower():
                str1 += character
            else:
                str2 += character
        elif character in "_.":
            str1 += character
        elif character in " |":
            str2 += character
    return str1, str2

Output: 输出:

>>> input_string = "'lMiED)teD5E,_hLAe;Nm,0@Dli&Eg ,#4aI?rN@T§&e7#4E #<(S0A?<)NT8<0'"
>>> 
>>> print f(input_string)
('lite_hemligare', 'MEDDELANDE INTE SANT')
>>> 

This is because you are iterating through a string. 这是因为您要遍历字符串。 The lowercase of the special characters is the same as the character. 特殊字符的小写字母与该字符相同。 ie. 即。 '#'.lower() == '#' . '#'.lower() == '#' hence it'll return '#' and all other special characters. 因此它将返回“#”和所有其他特殊字符。 you should explicitly check for alphabets using the isalpha() method on strings. 您应该在字符串上使用isalpha()方法显式检查字母。 (i.isalpha() and i.lower() == i) or i == '_' or i == '.'

You can use ASCII values for the filtering of characters: 您可以使用ASCII值来过滤字符:

def split_iterative(n):
    splitted_first = ""
    splitted_second = ""
    for i in n:
        if ord(i) in range(97,122) or i == "_" or i == ".":
            splitted_first = splitted_first + i
        elif ord(i) in range(65,90) or i == " " or i == "|":
            splitted_second = splitted_second + i
    return (splitted_first , splitted_second)

First, to make it return a list don't return the concatenated string but a list 首先,要使其返回列表,请不要返回连接的字符串,而要返回列表

Second, you are not checking or filtering out the characters, one way would be by checking if the character is a letter using isalpha() method 其次,您不是在检查或过滤掉字符,一种方法是使用isalpha()方法检查字符是否为字母

something like this: 像这样的东西:

def split_iterative(n):
splitted_first = ""
splitted_second = ""
for i in n:
    if (i.isalpha() and i == i.lower()) or i == "_" or i == ".":
        splitted_first = splitted_first + i
    elif (i.isalpha() and i == i.upper()) or i == " " or i == "|":
        splitted_second = splitted_second + i
#returns a list you can make it a variable if you need
return [splitted_first, splitted_second] 

You can make use of two lists while walking through characters of your text. 在浏览文本字符时,可以使用两个列表。

You can append lowercase, underscore, and stop characters to one list then uppercase, space and pipe characters to the other. 您可以在一个列表中附加小写,下划线和停止字符,然后在另一列表中附加大写,空格和竖线字符。

Finally return a tuple of each list joined as strings. 最后,以字符串形式返回每个列表的元组。

def splittext(txt):
  slug, uppercase_letters = [], []
  slug_symbols = {'_', '.'}
  uppercase_symbols = {' ', '|'}

  for letter in txt:
    if letter.islower() or letter in slug_symbols:
      slug.append(letter)
    if letter.isupper() or letter in uppercase_symbols:
      uppercase_letters.append(letter)

  return ''.join(slug), ''.join(uppercase_letters)


txt="'lMiED)teD5E,_hLAe;Nm,0@Dli&Eg ,#4aI?rN@T§&e7#4E #<(S0A?<)NT8<0'"
assert splittext(txt) == ("lite_hemligare", "MEDDELANDE INTE SANT")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:在某些索引处循环列表(包含某些字符串) - Python: looping through a list at certain indices (containing certain string) 使用Python只保留字符串中的某些字符? - Keeping only certain characters in a string using Python? 循环遍历字符串项列表并返回包含python中子字符串的字符串项 - looping through a list of string items and returning those that contain a substring in python 尝试从具有奇怪字符的文件中读取某些文本。 (蟒蛇) - Trying to read certain text from a file that has strange characters. (Python) 在python中的列表中解析以某些字符开头且长度为N的字符串 - Parse through list in python for string that starts with certain characters and is length N 如果任一字符串包含以下字符,则不能在 if 语句中使用布尔运算符“或”来启动。 仅适用于单独的语句 - Cant use the Boolean operator 'or' in a if statement to initiate if either string contains the following characters. Only works if separate statements 如何在 Python 中的字符串中只允许数字、字母和某些字符? - How to only allow digits, letters, and certain characters in a string in Python? 遍历具有int值的字符串的字符 - Looping through characters of a string with int values 在 Python 中,如何检查字符串是否只包含某些字符? - In Python, how to check if a string only contains certain characters? 检查字符串的“alpha”部分是否仅包含特定的字符序列 - python - Check that the "alpha" part of a string consists of only a certain sequence of characters - python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM