This question already has answers here:
String concatenation without '+' operator
(6 answers)
Closed 6 years ago.
These work for creating a string by defining it's individual elements separately:
str1 = ("a" "b")
# str1 = 'ab'
str2 = ("d"+str1)
# str2 = 'dab'
str3 = ("d" "e" "f")
# str3 = 'def'
But this one fails. Why so?
str3 = ("d"+str1 "e")
# SyntaxError: invalid syntax
What's the work around it?
You're mixing two different things. ("a" "b") looks like it's two strings, but it's really only one; string literals separated by whitespace are automatically concatenated to a single string. It's identical to using ("ab").
On the other hand, you can add two different strings to make a new single string. That's what's happening with ("d"+str1).
The trick in the first example only works with string literals, not with variables or more complicated expressions. So ("d"+str1 "e") doesn't work. You need ("d"+str1+"e"), which is two additions.
P.S. the parentheses are optional, they just group together operations that don't need any additional grouping.
Two string literals next to each other are automatically concatenated; this only works with two literals, not with arbitrary string expressions:
>>> 'str' 'ing' # <- This is ok
'string'
>>> 'str'.strip() + 'ing' # <- This is ok
'string'
>>> 'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
The Python Tutorial
More clearer:
Related
This question already has answers here:
Why is it string.join(list) instead of list.join(string)?
(11 answers)
Closed 5 months ago.
What is the significance of ("") before join method??
What I know is that we use "".join. But here the code is working fine if though ("") is used. Someone please explain.
("").join([map_s_to_t[s[i]] for i in range(len(s))])
Following is my whole code...
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(set(s)) != len(set(t)):
return False
# Create a mapping of chars from s -> t
map_s_to_t = { s[i]: t[i] for i in range(len(s)) }
# Create a new string by replacing the chars in s with t
s_replaced_with_t = ("").join([map_s_to_t[s[i]] for i in range(len(s))])
# if the replaced string is same as t , then True else False
return(s_replaced_with_t == t)
("").join and "".join has no difference at all. Enclosing empty string "" inside parenthesis just makes it an expression and is same as if there was no parenthesis.
For your reference, (1) is same as 1, and parenthesis is mainly used for including some expression, and if you use some IDE like Pycharm/VS Code, it will show you some warning as Redundant Parenthesis for ("")
join concatenates words and you pass the separator, so if you have "abc".join(['foo', 'bar']) then the result is
fooabcbar
The empty string passed as a parameter specifies that nothing will be put in between the elements. The paranthesis is not necessary around the separator.
This question already has answers here:
What are non-word boundary in regex (\B), compared to word-boundary?
(2 answers)
Closed 3 years ago.
I want to split my string into pieces but every some text and a special character. I have a string:
str = "ImEmRe#b'aEmRe#b'testEmRe#b'string"
I want my string to be split every EmRe#b' characters as you can see it contais the ' and that's the problem.
I tried doing re.split(r"EmRe#b'\B", str), re.split(r"EmRe#b?='\B", str) and also I tried both of them but without the r before the pattern. How do I do it? I'm really new to regular expressions. I would even say I've never used them.
Firstly, change the name of your variable, since str() is a built-in Python function.
If you named your variable word, you could get a list of elements split by your specified string by doing this:
>>> word = "ImEmRe#b'aEmRe#b'testEmRe#b'string"
>>> word
"ImEmRe#b'aEmRe#b'testEmRe#b'string"
>>> word.split("EmRe#b'")
['Im', 'a', 'test', 'string']
Allowing you to use them in many more ways than just a string! It can be saved to a variable, of course:
>>> foo = word.split("EmRe#b'")
>>> foo
['Im', 'a', 'test', 'string']
This question already has answers here:
How do the .strip/.rstrip/.lstrip string methods work in Python?
(4 answers)
Closed 4 years ago.
Is there a reason why I am having this kind of string strip behavior ? Is this a bug or some string magic I am missing
# THIS IS CORRECT
>>> 'name.py'.rstrip('.py')
'name'
# THIS IS WRONG
>>> 'namey.py'.rstrip('.py')
'name'
# TO FIX THE ABOVE I DID THE FOLLOWING
>>> 'namey.py'.rstrip('py').rstrip('.')
'namey'
That's because the str.rstrip() command removes each trailing character, not the whole string.
https://docs.python.org/2/library/string.html
string.rstrip(s[, chars])
Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
This also generates same result
>>> 'nameyp.py'.rstrip('.py')
'name'
You could try str().endswith
>>> name = 'namey.py'
... if name.endswith('.py'):
... name = name[:-3]
>>> name
'namey'
Or just str().split()
>>> 'namey.py'.split('.py')[0]
'namey'
This question already has answers here:
Changing one character in a string
(15 answers)
Closed 4 years ago.
Suppose I have the string x='abcd'. I want to replace the first and last letters of the string with c so that it becomes x='cbcc'. I'm a beginner at programming so I do not know how to do this.
You use indexing to access the first and last letters:
>>> s = "hello"
>>> s[0]
'h'
>>> s[-1]
'o'
However, you can't assign different characters to string literals:
>>> s[0] = "x"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
You must rebuild the string:
>>> s = "x" + s[1:]
>>> s
'xello'
Where s[1:] splices the string from the first character to the end.
I hope this helps you with your task.
In Python, strings are immutable. This means you can't simply jump in and change one part of a string. What you can do is select a specific part of a string (called a slice) and add strings (in this case individual characters) to either end of the slice.
What I am doing below is selecting all of the characters of the string except the first and last, and then adding the desired strings to each end.
Try this:
x='abcd'
new_x = 'c' + x[1:-1] + 'c'
Also, note that while I have created a new variable new_x, you could also reassign the this new string to the original variable name, i.e., x = 'c' + x[1:-1] + 'c'
This question already has answers here:
How can I do a line break (line continuation) in Python?
(10 answers)
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 5 months ago.
I have some strings to be concatenated and the resultant string will be quite long. I also have some variables to be concatenated.
How can I combine both strings and variables so the result would be a multiline string?
The following code throws error.
str = "This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3" ;
I have tried this too
str = "This is a line" \
str1 \
"This is line 2" \
str2 \
"This is line 3" ;
Please suggest a way to do this.
There are several ways. A simple solution is to add parenthesis:
strz = ("This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3")
If you want each "line" on a separate line you can add newline characters:
strz = ("This is a line\n" +
str1 + "\n" +
"This is line 2\n" +
str2 + "\n" +
"This is line 3\n")
Python 3: Formatted Strings
As of Python 3.6 you can use so-called "formatted strings" (or "f strings") to easily insert variables into your strings. Just add an f in front of the string and write the variable inside curly braces ({}) like so:
>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'
To split a long string to multiple lines surround the parts with parentheses (()) or use a multi-line string (a string surrounded by three quotes """ or ''' instead of one).
1. Solution: Parentheses
With parentheses around your strings you can even concatenate them without the need of a + sign in between:
a_str = (f"This is a line \n{str1}\n"
f"This is line 2 \n{str2}\n"
f"This is line 3") # no variable in this line, so a leading f"" is optional but can be used to properly align all lines
Good to know: If there is no variable in a line, there is no need for a leading f for that line.
Good to know: You could archive the same result with backslashes (\) at the end of each line instead of surrounding parentheses but accordingly to PEP8 you should prefer parentheses for line continuation:
Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
2. Solution: Multi-Line String
In multi-line strings you don't need to explicitly insert \n, Python takes care of that for you:
a_str = f"""This is a line
{str1}
This is line 2
{str2}
This is line 3"""
Good to know: Just make sure you align your code correctly otherwise you will have leading white space in front each line.
By the way: you shouldn't call your variable str because that's the name of the datatype itself.
Sources for formatted strings:
What's new in Python 3.6
PEP498
Python isn't php and you have no need to put $ before a variable name.
a_str = """This is a line
{str1}
This is line 2
{str2}
This is line 3""".format(str1="blabla", str2="blablabla2")
I would add everything I need to concatenate to a list and then join it on a line break.
my_str = '\n'.join(['string1', variable1, 'string2', variable2])