Hack Forums
[Python] New line every time X letter is met - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] New line every time X letter is met (/showthread.php?tid=5767397)



New line every time X letter is met - Divined - Dec 12, 2017

So if I want to make a new line every time the letter A is ran into in a line, what would the proper code be for that? I can't figure it out with regex.


RE: New line every time X letter is met - Vanagander - Dec 13, 2017

Not sure what you're asking for here..
The regex to find the letter a, upper- and lowercase is [Aa].


RE: New line every time X letter is met - michalmonday - Dec 13, 2017

@Divined

Code
s = "uuuuuuuuuuuuuuAuuuuuuuuuAuuuuuAu"
new_s = "\nA".join(s.split("A"))
print(new_s)

the output is:
Code
uuuuuuuuuuuuuu
Auuuuuuuuu
Auuuuu
Au
string.split("A") returns a list of strings separated by the given piece of text ("A" in this case)
string.join(list) joins list items by placing the string between them

Actually this way looks better to me, it uses regex pattern (r"A") instead which makes it easier to search for specific types of characters within the text, and it's just one function working on the string instead of splitting into a list and joining it again.

Code
import re
s = "uuuuuuuuuuuuuuAuuuuuuuuuAuuuuuAu"
new_s = re.sub(r"A", "\nA", s)
print(new_s)