Python string concatenation of multiple strings separated without comma [duplicate] - python

This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 3 years ago.
Though it might seem a very trivial question, I still want to know the principle behind it. When we write multiple strings together without any comma,python concatenates them. I was under the impression that it will throw some error. Below is a sample output:
print('hello''world')
# This will output helloworld
Even if I write those multiple strings in the python REPL, the output will be the concatenated form of the strings. Can anyone please explain the logic behind this operation ?

See https://docs.python.org/3.8/reference/lexical_analysis.html#string-literal-concatenation.
Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation.
Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings

Related

How to concatenate char with numbers via loops [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 6 years ago.
I have make a set of names in this form: 's1', 's2', ..., 's100'. I thought I can do that easily via looping:
for i in range(100):
print ('s'.format(i+1))
format here does not append the numbers. I only get ss..ss without the numbers being concatenated in single quote. I know how to do this in Java but I am not that much expert in Python. Thank you
You need to have a placeholder in the format string:
Perform a string formatting operation. The string on which this method
is called can contain literal text or replacement fields delimited by
braces {}. Each replacement field contains either the numeric index of
a positional argument, or the name of a keyword argument.
for i in range(100):
print ('s{0}'.format(i+1))
If you use 3.6, then you can take advantage of the new 'Literal String Interpolation', and do the following:
for i in range(100):
print(f's{i + 1}')
For more details on this feature, check out PEP 498 -- Literal String Interpolation

How to use string slicing inside string.format [duplicate]

This question already has answers here:
Slicing strings in str.format
(6 answers)
Closed 6 years ago.
How can I do variable string slicing inside string.format like this.
"{0[:2]} Some text {0[2:4]} some text".format("123456")
Result I want result like this.
12 Some text 34 some text
You can't. Best you can do is limit how many characters of a string are printed (roughly equivalent to specifying a slice end), but you can't specify arbitrary start or end indices.
Save the data to a named variable and pass the slices to the format method, it's more readable, more intuitive, and easier for the parser to identify errors when they occur:
mystr = "123456"
"{} Some text {} some text".format(mystr[:2], mystr[2:4])
You could move some of the work from that to the format string if you really wanted to, but it's not a huge improvement (and in fact, involves larger temporaries when a slice ends up being needed anyway):
"{:.2s} Some text {:.2s} some text".format(mystr, mystr[2:])

String syntax allows two strings in a row with no operator? [duplicate]

This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 7 years ago.
I just discovered what I thought was a typo but Python accepts it.
foo = {'a': 'b'}
foo.get('a'"")
returns 'b'. Where in Python is 'a'"" defined as a valid parameter to a function?
Python concatenates all consecutive strings. It doesn't matter if that's in a function or elsewhere.
See the String literal concatenation section of the reference documentation:
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation.
This is done at the parsel level; the final bytecode stores just the one string object. See What is under the hood of x = 'y' 'z' in Python?
The feature was copied from C. From a (failed) proposal to remove the feature:
Many Python parsing rules are intentionally compatible with C. [...] In C, implicit concatenation is the only way to join strings without using a (run-time) function call to store into a variable.
The feature is very useful when producing long strings:
long_value = (
'The quick brown fox jumped over the lazy fox and kept '
'the string within the 80 character boundary.'
)

Correct way of commenting on commands in python [duplicate]

This question already has answers here:
Python comments: # vs. strings
(3 answers)
Closed 9 years ago.
I know two ways of leaving comments in python. One is using """ and the other is using #. I know that the first can be used to return a functions help as a benefit. But when should I use one and when the other? And also how do I have to leave comments? Do I have to press tab and arrange the first line of comment with the the command beneath it? Or do I have to start from the beginning of the line?
No, there is only one way of commenting, using #:
A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line.
Triple quoting, """, creates a string object, which happens to be used as the docstring when it is the first line of a function, module or a a class. Triple quoting is useful in many other places too, but should not be confused with commenting. You can use a triple quoted string like any other string literal, with the specific benefit that you can use actual newlines in your source code instead of having to use \n escape characters.
Although it can be used to disable a block of code by turning it into a multi-line string instead, you really should not do this. Use proper source code control and simply delete the block, or use an editor that lets you comment out whole blocks by inserting # for you instead.
For actual comments, use #. The Python style guide (PEP 8) has some things to say about when and how to use commenting; it has this to say about indentation:
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).

python string good practise: ' vs " [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Single quotes vs. double quotes in Python
I have seen that when i have to work with string in Python both of the following sintax are accepted:
mystring1 = "here is my string 1"
mystring2 = 'here is my string 2'
Is anyway there any difference?
Is it by any reason better use one solution rather than the other?
Cheers,
No, there isn't. When the string contains a single quote, it's easier to enclose it in double quotes, and vice versa. Other than this, my advice would be to pick a style and stick to it.
Another useful type of string literals are triple-quoted strings that can span multiple lines:
s = """string literal...
...continues on second line...
...and ends here"""
Again, it's up to you whether to use single or double quotes for this.
Lastly, I'd like to mention "raw string literals". These are enclosed in r"..." or r'...' and prevent escape sequences (such as \n) from being parsed as such. Among other things, raw string literals are very handy for specifying regular expressions.
Read more about Python string literals here.
While it's true that there is no difference between one and the other, I encountered a lot of the following behavior in the opensource community:
" for text that is supposed to be read (email, feeback, execption, etc)
' for data text (key dict, function arguments, etc)
triple " for any docstring or text that includes " and '
No. A matter of style only. Just be consistent.
I tend to using " simply because that's what most other programming languages use.
So, habit, really.
There's no difference.
What's better is arguable. I use "..." for text strings and '...' for characters, because that's consistent with other languages and may save you some keypresses when porting to/from different language. For regexps and SQL queries, I always use r'''...''', because they frequently end up containing backslashes and both types of quotes.
Python is all about the least amount of code to get the most effect. The shorter the better. And ' is, in a way, one dot shorter than " which is why I prefer it. :)
As everyone's pointed out, they're functionally identical. However, PEP 257 (Docstring Conventions) suggests always using """ around docstrings just for the purposes of consistency. No one's likely to yell at you or think poorly of you if you don't, but there it is.

Categories

Resources