How can I change a string. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How can I change a string. (/thread-27328.html) |
How can I change a string. - Mike Ru - Jun-03-2020 I have a string. I need to find words and change them if it there are over there. I am trying something like this. But I doesn't work. I need to get new string something like this. When parents go. What do they listen to. Why var = 'When parents goWhat do they listen toWhy' words = ['When', 'Why', 'What', 'How'] def check(a): s = [] for x in a: for j in words: if j in x: s.append(foo(x)) return s def foo(a): first = list(a)[0] var = list(a)[1:] new = [] for x in var: if x.isupper(): new.append('. ') new.append(x) else: new.append(x) new_string = first + ''.join(new) return new_string var = var.split(' ') print(check(var))How can I do this correctly ? RE: How can I change a string. - buran - Jun-03-2020 var = 'When parents goWhat do they listen toWhy' words = ['When', 'Why', 'What', 'How'] for word in words: if not var.startswith(word): var = var.replace(word, f'. {word}') print(var) RE: How can I change a string. - Mike Ru - Jun-03-2020 (Jun-03-2020, 10:13 AM)buran Wrote:var = 'When parents goWhat do they listen toWhy' words = ['When', 'Why', 'What', 'How'] for word in words: if not var.startswith(word): var = var.replace(word, f'. {word}') print(var) Thank you so much. There is one 'but'. For example: if the string has When parents goWhat do they listen toWhy How How to do not to set '.' in front of 'How' ? output: When parents go. What do they listen to. Why How
RE: How can I change a string. - buran - Jun-03-2020 well this breaks the example both in terms of example input and expected output. It breaks the example input as I understood it - a word in words list is concatenated to previous word, i.e. my understandig was the input would be When parents goWhat do they listen toWhyHow It breaks the expected output as I understood it - a word in list is preceded by dot and space, i.e. making a complete sentence. When parents go. What do they listen to. Why. How All that said - define explicit rules how the input string will look like and what the expected output should be and then a more complex parser should be created |