python how do i use my string in a for loop - python

i have a few strings that hold a value. i.e.
how can i loop though multiple string1,string2,string3 etc?
string1 = re.findall('qr="">(.*?)</span', str(raw[1]))
string2 = re.findall('qr="">(.*?)</span', str(raw[2]))
string3 = re.findall('qr="">(.*?)</span', str(raw[3]))
for i in x:
print(i)
i would like for it to print the value of string1,string2,string3
i have tried to store string1 - string3 in a list but with ut success.

Try Something like this perhaps
strings = []
string1 = re.findall('qr="">(.*?)</span', str(raw[1]))
string2 = re.findall('qr="">(.*?)</span', str(raw[2]))
string3 = re.findall('qr="">(.*?)</span', str(raw[3]))
strings.append(string1)
strings.append(string2)
strings.append(string3)
for i in strings:
print(i)

Related

Assert only if an entire word is filled out

string1 = "Billie Jean"
string2 = " "
teststring = string2.split(" ")
for word in teststring:
if word in string1:
return True
return False
Can I make it so that if string2 is for example: "Baby Jean" it's true, but if it's: "ea" it returns as false?
I believe the resolution is to split up string1 into a list of words before performing an in check, as follows:
string1 = "Billie Jean"
string2 = " "
string3 = 'Baby Jean'
words1 = string1.split()
def check(string):
teststring = string.split()
for word in teststring:
# Notice that we iterate over a list of words instead of string1
if word in words1:
return True
return False
print(check(string2))
print(check(string3))
Another option would be to use the set.intersection method, which returns true if there are any shared elements between two collections (one of which is a set):
string1 = "Billie Jean"
string2 = " "
string3 = 'Baby Jean'
words1 = set(string1.split())
def check(string):
return True if words1.intersection(string.split()) else False
print(check(string2))
print(check(string3))
Outputs:
False
True
A couple of pointers:
split() by default splits on the " " character so you don't need to explicitly pass it.
Since you are checking for word being in another string, you must split string1 too.
Check the code below:
def func(string1, string2):
for word in string2.split():
if word in string1.split():
return True
return False
print(func("Billie Jean", "Baby Jean")) # True
print(func("Billie Jean", "ea")) # False
A more interesting solution would be the following:
def func(string1, string2):
# create set of words for each string and see if intersection is empty or not
return True if set(string1.split()) & set(string2.split()) else False
print(func("Billie Jean", "Baby Jean"))
print(func("Billie Jean", "ea"))
Since matching using the intersection of sets leverages hashing, this method will be a lot faster at scale. (Might not really matter to you know, but it is good to know)
PS. You might want to convert both strings to the same case (lower or upper) if you wish to match "Jean" with "jean".

Replacing spaces in one string with characters of other string

Say I have two strings, string1="A B C " and string2="abc". How do combine these two strings so string1 becomes "AaBbCc"? So basically I want all the spaces in string1 to be replaced by characters in string2. I tried using two for-loops like this:
string1="A B C "
string2="abc"
for char1 in string1:
if char1==" ":
for char2 in string2:
string1.replace(char1,char2)
else:
pass
print(string1)
But that doesn't work. I'm fairly new to Python so could somebody help me? I use version Python3. Thank you in advance.
You can use iter on String2 and replace ' ' with char in String2 like below:
>>> string1 = "A B C "
>>> string2 = "abc"
>>> itrStr2 = iter(string2)
>>> ''.join(st if st!=' ' else next(itrStr2) for st in string1)
'AaBbCc'
If maybe len in two String is different you can use itertools.cycle like below:
>>> from itertools import cycle
>>> string1 = "A B C A B C "
>>> string2 = "abc"
>>> itrStr2 = cycle(string2)
>>> ''.join(st if st!=' ' else next(itrStr2) for st in string1)
'AaBbCcAaBbCc'
string1 = "A B C "
string2 = "abc"
out, repl = '', list(string2)
for s in string1:
out += s if s != " " else repl.pop(0)
print(out) #AaBbCc

How to check if individual character in a string exists in another string for python

Is there any library that allows me to check If all the individual characters in one string exists in another string. When i try to use in what happens is the character has to be a substring. It only works for 1234 and 123. However i want something that checks individual characters. I want a library that gives me the output: string 2 is in string 1 for the following code.
string1 = '1234'
string2 = '24'
if string2 in string1:
print('string2 is in string1')
else:
print('string2 is not in string1')
You can use all() with a generator. This returns a true only if all conditions are a true else false:
string1 = '1234'
string2 = '24'
if all(x in string1 for x in string2):
print('string2 is in string1')
else:
print('string2 is not in string1')
Or, you can use set's issubset:
set(string2).issubset(string1)

Python elif not working as expected for string find

I would like to pull out the locations for an inconsistently formatted data field in a Pandas dataframe. (I do not maintain the data so I cannot alter how this field is formatted.)
Running the following toy version
string2 = 'Denver.John'
if string2.find(' -'):
string2 = string2.split(' -')[0]
elif string2.find('.'):
string2 = string2.split('.')[0]
print(string2)
gives me Denver.John instead of Denver. However, if I use an if instead:
string2 = 'Denver.John'
if string2.find(' -'):
string2 = string2.split(' -')[0]
if string2.find('.'):
string2 = string2.split('.')[0]
print(string2)
I get Denver, as desired. The problem is I also have strings like 'Las.Vegas - Rudy' and I want to be able to pull out Las.Vegas in those instances so I only want to split on a period if the field does not contain the hyphen (' - ').
Why does the elif not work for Denver.John?
Because find either yields the index or -1 while -1 is valid!!!, so try using:
string2 = 'Denver.John'
if string2.find(' -') + 1:
string2 = string2.split(' -')[0]
elif string2.find('.') + 1:
string2 = string2.split('.')[0]
print(string2)
Or better like:
string2 = 'Denver.John'
if ' -' in string2:
string2 = string2.split(' -')[0]
elif '.' in string2:
string2 = string2.split('.')[0]
print(string2)
Use
if ' -' in string2
instead. The find method returns an int
find() returns the lowest index of the substring if it is found in given string. If it’s not found then it returns -1.
So in your case:
string2 = 'Denver.John'
print(string2.find(' -')) # prints -1
print(string2.find('.')) # prints 6
if string2.find(' -'):
string2 = string2.split(' -')[0]
elif string2.find('.'):
string2 = string2.split('.')[0]
print(string2)
So in your if statement you can compare the result of find with -1.
string.find returns a position of the substring, and it is -1 if it doesn't find the substring.
Thus, do the following instead:
string2 = 'Denver.John'
if string2.find(' -') >= 0:
string2 = string2.split(' -')[0]
elif string2.find('.') >= 0:
string2 = string2.split('.')[0]
print(string2)

regex between some character

input:
[1] string1 [2] string 2[3]string3 [5]string4
output:
string1
string 2
string 4
how to resolve the case as "input" and the result "output" with "regex" python?
Your instructions are a bit vague, that said - using the example input you provided:
import re
line = '[1] string1 [2] string 2[3]string3 [5]string4'
matches = re.match(r'\[1\] (.*?)\[2\] (.*?)\[3\](.*?)\[5\](.*)', line)
print matches.group(1) # prints string1
print matches.group(2) # prints string 2
print matches.group(3) # prints string3
print matches.group(4) # prints string4
It seems like you don't want the value of an index if it is preceded by a character other than white space or a starting anchor ,
>>> s = "[1] string1 [2] string 2[3]string3 [5]string4"
>>> import regex
>>> m = regex.findall(r'(?<= |^)\[\d+\]\s*([^\[]*)', s)
>>> for i in m:
... print i
...
string1
string 2
string4

Categories

Resources