Split long dictionary value over two lines [duplicate] - python

This question already has answers here:
How do I split the definition of a long string over multiple lines?
(30 answers)
Closed 9 months ago.
Very new to python here. How do you split a very long dictionary value over two lines while still having it appear as one line when it is output with print()? See code below.
glossary = {'dictionary' : 'A mutable associative array (or dictionary) of key and value pairs. Can contain mixed types (keys and values). Keys must be a hashable type'}
I've tried using triple quotes (i.e. """) with no success since I don't think the value is technically a string.

you can use \ (backslash) to continue code onto the next line
e.g.
print("hello \
how are you")
would return
hello how are you
edit: you should be able to use """ as (from my understanding) it just converts it to a normal string but adds the line breaks. this wouldnt give the result you wanted but it should work
edit: just tested the above:
list = ['hi', '''thing1
thing2''']
print(list)
ouput:
['hi', 'thing1\nthing2']
that \n means newline so i would use the backslash as i mentioned above if you want the correct output

Related

Reversing/mirroring special characters in Python [duplicate]

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.

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.

What is the difference between multi-line comment and multi-line string in python? [duplicate]

This question already has answers here:
Python comments: # vs. strings
(3 answers)
Closed 6 years ago.
I am still exploring python. Today I came across multi-line strings. If I do:
a = '''
some-text
'''
The content of variable a is '\nsome-text\n'. But this leaves me confused. I always thought that if you enclose something within three single quotes ('''), you are commenting it out. So the above statement would be equivalent to something like this in C++:
a = /*
some-text
*/
What am I missing?
Technically such multi-line-comments enclosed in triple quotes are not really comments but string literals.
The reason why you can still use them to comment stuff out is that a string literal itself does not represent any kind of operation. It gets parsed, but nothing is done with it and it does not get assigned to a variable name, so it gets ignored.
You could also place any other literal into your code. As long as it is not involved in any kind of operation or assignment, it gets basically ignored like a comment. It is not a comment though, just useless code if you want to name it that way.
Here's an example of code that does... well, nothing:
# This is a real comment.
"useless normal string"
"""useless triple-quoted
multi-line
string"""
[1, "two"] # <-- useless list
42 # <-- useless number
I always thought that if you enclose something within three single quotes (''')
This is not the case, actually. Enclosing something in triple quotes '''string''', it creates a string expression which yields a string containing the characters within the quotes. The difference between this and a single quoted string 'string' is that the former can be on multiple lines. People often use this to comment out multiple lines.
However, if you don't assign the string expression to a variable, then you'll get something a lot like a comment.
'''this is
a useless piece of python
text that does nothing for
your program'''
In python, wrapping your code with ''' will encode it as a string, effectively commenting it out unless that code already contains a multi-line string literal ''' anywhere. Then, the string will be terminated.
print('''hello!
How are you?''')
# this will not have the intended comment effect
'''
print('''hello!
How are you?''')
'''

Adding thousand separator while printing a number [duplicate]

This question already has answers here:
How to print a number using commas as thousands separators
(30 answers)
Closed 9 years ago.
I don't really know the "name" for this problem, so it might be a incorrect title, but the problem is simple, if I have a number
for example:
number = 23543
second = 68471243
I want to it make print() like this.
23,543
68,471,243
I hope this explains enough or else add comments.
Any help is appreciated!
If you only need to add comma as thousand separator and are using Python version 3.6 or greater:
print(f"{number:,g}")
This uses the formatted string literals style. The item in braces {0} is the object to be formatted as a string. The colon : states that output should be modified. The comma , states that a comma should be used as thousands separator and g is for general number. [1]
With older Python 3 versions, without the f-strings:
print("{0:,g}".format(number))
This uses the format-method of the str-objects [2]. The item in braces {0} is a place holder in string, the colon : says that stuff should be modified. The comma , states that a comma should be used as thousands separator and g is for general number [3]. The format-method of the string object is then called and the variable number is passed as an argument.
The 68,471,24,3 seems a bit odd to me. Is it just a typo?
Formatted string literals
Python 3 str.format()
Python 3 Format String Syntax
The easiest way is setting the locale to en_US.
Example:
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
number = 23543
second = 68471243
print locale.format("%d", number, grouping=True)
print locale.format("%d", second, grouping=True)
prints:
23,543
68,471,243

Categories