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.
Related
This question already has answers here:
Keeping only certain characters in a string using Python?
(3 answers)
Closed 1 year ago.
I'm just a beginner so this might be a stupid question but, I'm trying to remove every character from a string except the ones in a list
for example:
you have a string H][e,l}l.o1;4.I want only letters and numbers in the output.
It should look like this:
Hello14
Does anyone have any idea what needs to come behind the str1 = or any other methods?
This is what I tried so far:
def stringCleaner(s):
# initialize an empty string
str1 = " "
chars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
for x in range(len(s)):
if any((c in chars) for c in s):
str1=
return str1
It will be better to simply iterate over your input string and create a list of allowed characters and join() the list into a string again at the end.
def stringCleaner(s):
# initialize an empty list
str1 = []
chars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
for c in s:
if c in chars:
str1.append(c)
return ''.join(str1)
And then you should be able to see that its only a few short steps to get even better code such as the answer that #user1740577 has posted.
You can for any char in s check in chars list and .join() all of them if exist in chars list.
Try this:
def stringCleaner(s):
chars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
return ''.join(c for c in s if c in chars)
stringCleaner('H][e,l}l.o1;4.I')
# 'Hello14I'
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:
This question already has answers here:
Python Regex to find a string in double quotes within a string
(6 answers)
Closed 6 years ago.
I'm trying to write a function where the input has a keyword that occurs multiple times in a string and will print the stuff that has double quotation marks between them after the keyword. Essentially...
Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
Output= someonehelpmepls
itonlygivesmeoneinsteadofmultiple
If its possible to have the outputs as its own line that would be better.
Here's what I have so far:
def getEm(s):
h = s.find('keyword')
if h == -1
return -1
else:
begin = s.find('"',h)
end = s.find('"', begin+1)
result = s[begin +1:end]
print (result)
Please don't suggest import. I do not know how to do that nor know what it is, I am a beginner.
Let's take some sample input:
>>> Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
I believe that one " was missing from the sample input, so I added it.
As I understand it, you want to get the strings in double-quotes that follow the word keyword. If that is the case, then:
def get_quoted_after_keyword(input):
results = []
split_by_keyword = input.split('keyword')
# you said no results before the keyword
for s in split_by_keyword[1:]:
split_by_quote = s.split('"')
if len(split_by_quote) > 1:
# assuming you want exactly one quoted result per keyword
results.append(split_by_quote[1])
return results
>print('\n'.join(get_quoted_after_keyword(Input))
>someonehelpmepls
>itonlygivesmeoneinsteadofmultiple
How it works
Let's look at the first piece:
>>> Input.split('keyword')
['alkfjjie',
' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
By splitting Input on keyword, we get, in this case, three strings. The second string to the last are all strings that follow the word keyword. To get those strings without the first string, we use subscripting:
>>> Input.split('keyword')[1:]
[' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
Now, our next task is to get the part of these strings that is in double-quotes. To do that, we split each of these strings on ". The second string, the one numbered 1, will be the string in double quotes. As a simpler example, let's take these strings:
>>> [s.split('"')[1] for s in ('"one"otherstuff', ' "two"morestuff')]
['one', 'two']
Next, we put these two steps together:
>>> [s.split('"')[1] for s in Input.split('keyword')[1:]]
['someonehelpmepls', 'itonlygivesmeoneinsteadofmultiple']
We now have the strings that we want. The last step is to print them out nicely, one per line:
>>> print('\n'.join(s.split('"')[1] for s in Input.split('keyword')[1:]))
someonehelpmepls
itonlygivesmeoneinsteadofmultiple
Limitation: this approach assumes that keyword never appears inside the double-quoted strings.
This question already has answers here:
Check if multiple strings exist in another string
(17 answers)
Closed 7 years ago.
To check if a string contains a substring, one can use "in" like so:
if "abc" in str:
print("yay")
And to check if a string contains one of two substrings one can use "or" like so:
if "abc" in str or "def" in str:
print("yay")
My question is whether or not python has a way to simplify that into something like this:
if "abc" or "def" in str:
print("yay")
I know this won't work as intended because it will always evaluate to true. (Python will check for at least one of the two statements, either
"abc"
"def" in str
being true and "abc" will always evaluate to true)
Having said that, is there anyway to check for such a condition other than this, rather verbose, method:
if "abc" in str or "def" in str:
print("yay")
if any(word in sentence for word in {"abc", "def"}):
print("yay")
Put them in an array and do:
if any(x in word for x in a):
This has been answered here Check if multiple strings exist in another string
If your question is like whether there is a way, to check whether any string in given list of strings exist in a bigger string . We can use the any() function along with generator expressions for that.
Example -
>>> s = "Hello World Bye Abcd"
>>> l = ["Hello","Blah"]
>>> l1 = ["Yes","No"]
>>> any(li in s for li in l)
True
>>> any(li in s for li in l1)
False
This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 7 years ago.
I am a newbie in Python. I am making a program where I take a input from user and check if any number is inside in the string. I am checking it by taking it in a variable. Is it not correct to check via a VARIABLE?
user_string=input("Enter the Word:")
print (user_string)
for index in (0,9):
number=str(index) #Typecasting Int to String
if number in user_string: #Check if Number exist in the string
print ("yes")
output:
Enter the Word:helo2
helo2
You can use the string method isdigit() on each character in a generator expression within any. This will short-circuit upon finding the first numeric character (if one is present)
>>> user_string = 'helo2'
>>> any(i.isdigit() for i in user_string)
True
>>> user_string = 'hello'
>>> any(i.isdigit() for i in user_string)
False
Look at your for-loop. You are looping over a tuple (0,9). So actually you are only testing for 0 and 9. Use range(10) instead.
More elegant, to get the numbers inside your string, you can use sets:
import string
print 'yes' if set(string.digits).intersection(user_string) else 'no'