Reversing/mirroring special characters in Python [duplicate] - python

This question already has an answer here:
Modify a string by swapping multiple letters
(1 answer)
Closed 2 years ago.
I'd like to reverse/mirror special characters in Python.
Let's say my string is 'hello (one) sun {apple}'
My output string would have to be '{elppa} nus (eno) olleh'
Of course, with typical reversing, the outcome is '}elppa{ nus )eno( olleh' which is not what I need.
Is there any "easy" way to do this? Using regex, maybe?

So, basically you want the braces encapsulating the text to remain same and mirror everything else? In that case you can run a function after mirroring to revert all the braces. The easiest way would be to run the replace subroutine, like below:
line = line.replace('<', '!#!#')
line = line.replace('>', '<')
line = line.replace('!#!#', '>')
Here I am taking <> as an example, I replace '<' with '!#!#' temporarily, then replace '>' with '<', and then substitute '!#!#' with '>'.
Not a very robust method, but an easy quick fix.

Related

How to input a variable string into re.search in python [duplicate]

This question already has answers here:
How to use a variable inside a regular expression?
(12 answers)
Closed 4 years ago.
Initially I had my date regex working as follows, to capture "February 12, 2018" for example
match = re.search(r'(January|February|March|April|May|June|July|August|September?|October?|November|December)\s+\d{1,2},\s+\d{4}', date).group()
But I want it to become more flexible, and input my variable string into my regex but I can't seem to get it to work after looking through many of the stackoverflow threads about similar issues. I'm quite a novice so I'm not sure what's going wrong. I'm aware that simply MONTHS won't work. Thank you
MONTHS = "January|February|March|April|May|June|July|August|September|October|November|December"
match = re.search(r'(MONTHS)\s+\d{1,2},\s+\d{4}', date).group()
print(match)
'NoneType' object has no attribute 'group'
You've got MONTHS as just a part of the match string, python doesn't know that it's supposed to be referencing a variable that's storing another string.
So instead, try:
match = re.search(r'(' + MONTHS + ')\s+\d{1,2},\s+\d{4}', date).group()
That will concatenate (stick together) three strings, the first bit, then the string stored in your MONTHS variable, and then the last bit.
If you want to substitute something into a string, you need to use either format strings (whether an f-string literal or the format or format_map methods on string objects) or printf-style formatting (or template strings, or a third-party library… but usually one of the first two).
Normally, format strings are the easiest solution, but they don't play nice with strings that need braces for other purposes. You don't want that {4} to be treated as "fill in the 4th argument", and escaping it as {{4}} makes things less readable (and when you're dealing with regular expressions, they're already unreadable enough…).
So, printf-style formatting is probably a better option here:
pattern = r'(%s)\s+\d{1,2},\s+\d{4}' % (MONTHS,)
… or:
pattern = r'(%(MONTHS)s)\s+\d{1,2},\s+\d{4}' % {'MONTHS': MONTHS}

Output of print("""Hello World's"s""""") in python 3.6 [duplicate]

This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 4 years ago.
I read that anything between triple quotes inside print is treated literal so tried messing things a little bit. Now I am not able to get above statement working. I searched internet but could not find anything.
statement:
print("""Hello World's"s""""")
Output I am getting:
Hello World's"s
Expected output:
Hello World's"s""
print("""Hello World's"s""""") is seen as print("""Hello World's"s""" "") because when python find """ it automatically ends the previous string beginning with a triple double-quote.
Try this:
>>> print("a"'b')
ab
So basically your '"""Hello World's"s"""""' is just <str1>Hello World's"s</str1><str2></str2> with str2 an empty string.
Triple quoted string is usually used for doc-string.
As #zimdero pointed out Triple-double quote v.s. Double quote
You can also read https://stackoverflow.com/a/19479874/1768843
And https://www.python.org/dev/peps/pep-0257/
If you really want to get the result you want just use \" or just you can do combination with ``, .format() etc
print("Hello World's\"s\"\"")
https://repl.it/repls/ThatQuarrelsomeSupercollider
Triple quotes within a triple-quoted string must still be escaped for the same reason a single quote within a single quoted string must be escaped: The string parsing ends as soon as python sees it. As mentioned, once tokenized your string is equivalent to
"""Hello World's"s""" ""
That is, two strings which are then concatenated by the compiler. Triple quoted strings can include newlines. Your example is similar to
duke = """Thou seest we are not all alone unhappy:
This wide and universal theatre
Presents more woeful pageants than the scene
Wherein we play in."""
jaques = """All the world's a stage,
And all the men and women merely players:
They have their exits and their entrances;
And one man in his time plays many parts."""
If python was looking for the outermost triple quotes it would only have defined one string here.
Simple with ''' to not complicate things:
print('''Hello World's"s""''')
Maybe this is what you are looking for?
print("\"\"Hello World's's\"\"")
Output:
""Hello World's's""

How to change a word if it includes a certain letter [duplicate]

This question already has answers here:
Replacing instances of a character in a string
(17 answers)
Closed 5 years ago.
I tried to replace vowels and add il to them using this code but it didnt work, help!
line=input("What do you want to say?\n")
line = line.replace('e', 'ile')
line = line.replace('o', 'ilo')
line = line.replace('a', 'ila')
line = line.replace('i', 'ili')
line = line.replace('u', 'ilu')
line = line.replace('y', 'ily')
print (line)
But if you type a long sentence it stop working correctly.
could someone please help me?
Want to print "Hello world"
it prints:
Hililellililo wililorld
when should print Hilellilo Wilorld
Try replacing any occurrence of the letters you want with regex. Like this i.e:
import re
re.sub(r'[eE]', 'i$0', "Hello World")
You can replace any letter you want putting them inside the square brackets.
Additionally, that 'i$0' is the literal character 'i' and $0 the letter that was matched.
"Hello world".replace('e', 'ie')
But your question is not very clear, may be you mean something different.
Whenever you do multiple replacements after each other, you always need to be careful with the order in which you do them.
In your case put this replacement first:
line = line.replace('i', 'ili')
Otherwise it replaces the i's in the replacements that have been done before.
When you need to do many replacements it is often better to use an approach that avoids these problems.
One of them can be using regular expressions, as already proposed. Another is scanning the text from start to end for items to replace and replace each item when you find it during the scan and continue scanning after the replacement.

Can someone translate this code into Pseudo Code or something I can understand? [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 7 years ago.
I am not very familiar with regex(s) and would like somebody to put this into something that I will be able to understand? As in, outline what each part of the regex is doing
re.compile(r'ATG((?:[ACTG]{3})+?)(?:TAG|TAA|TGA)')
So far, this is what I have come up with:
re.compile is a regex method... or something along those lines
r' is simply needed in regex
After that, I'm not too sure...
Searches for a piece in the string ATG
?:[ACTG]{3} searches for a piece of the string containing the characters A C T G within the string (does the order of these matter?) that is {3} three characters long.
+? something about going at least once, but minimal times...? What would part of code would be going at least once, but minimal times?
?: searches for TAG|TAA|TGAwithin the string. Once it finds these, what does happens?
Would I be able to do something like
key_words = "TAG TAA TGA".replace(" ", "|") so that I can have a whole long list without having to type of | a bunch of times if I have over 100 substrings?
I would then format this to something like this:
...(?:key_words)')
Examples and simple explanations always work wonders - thanks!
You can use regex101 to have it explained step by step.

How can I print a string using .format(), and print literal curly brackets around my replaced string [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I print a literal “{}” characters in python string and also use .format on it?
Basically, I want to use .format(), like this:
my_string = '{{0}:{1}}'.format('hello', 'bonjour')
And have it match:
my_string = '{hello:bonjour}' #this is a string with literal curly brackets
However, the first piece of code gives me an error.
The curly brackets are important, because I'm using Python to communicate with a piece of software via text-based commands. I have no control over what kind of formatting the fosoftware expects, so it's crucial that I sort out all the formatting on my end. It uses curly brackets around strings to ensure that spaces in the strings are interpreted as single strings, rather than multiple arguments — much like you normally do with quotation marks in file paths, for example.
I'm currently using the older method:
my_string = '{%s:%s}' % ('hello', 'bonjour')
Which certainly works, but .format() seems easier to read, and when I'm sending commands with five or more variables all in one string, then readability becomes a significant issue.
Thanks!
Here is the new style:
>>> '{{{0}:{1}}}'.format('hello', 'bonjour')
'{hello:bonjour}'
But I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping:
>>> '{%s:%s}' % ('hello', 'bonjour')
'{hello:bonjour}'

Categories