This question already has answers here:
Find common characters between two strings
(5 answers)
Closed 2 months ago.
I have a string of text
hfHrpphHBppfTvmzgMmbLbgf
I have separated this string into two half's
hfHrpphHBppf,TvmzgMmbLbgf
I'd like to check if any of the characters in the first string, also appear in the second string, and would like to class lowercase and uppercase characters as separate (so if string 1 had a and string 2 had A this would not be a match).
and the above would return:
f
split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']
for char in split_text[0]:
if char in split_text[1]:
print(char)
There is probably a better way to do it, but this a quick and simple way to do what you want.
Edit:
split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']
found_chars = []
for char in split_text[0]:
if char in split_text[1] and char not in found_chars:
found_chars.append(char)
print(char)
There is almost certainly a better way of doing this, but this is a way of doing it with the answer I already gave
You could use the "in" word.
something like this :
for i in range(len(word1) :
if word1[i] in word2 :
print(word[i])
Not optimal, but it should print you all the letter in common
You can achieve this using set() and intersection
text = "hfHrpphHBppf,TvmzgMmbLbgf"
text = text.split(",")
print(set(text[0]).intersection(set(text[1])))
You can use list comprehension in order to check if letters from string a appears in string b.
a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[x for x in a if x in b]
print(' '.join(set(c)))
then output will be:
f
But you can use for,too. Like:
a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[]
for i in a:
if i in b:
c.append(i)
print(set(c))
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:
How do I reverse a string in Python?
(19 answers)
Closed 2 years ago.
I am trying to create a program in which the user inputs a statement containing two '!' surrounding a string. (example: hello all! this is a test! bye.) I am to grab the string within the two exclamation points, and print it in reverse letter by letter. I have been able to find the start and endpoints that contain the statement, however I am having difficulties creating an index that would cycle through my variable userstring in reverse and print.
test = input('Enter a string with two "!" surrounding portion of the string:')
expoint = test.find('!')
#print (expoint)
twoexpoint = test.find('!', expoint+1)
#print (twoexpoint)
userstring = test[expoint+1 : twoexpoint]
#print(userstring)
number = 0
while number < len(userstring) :
letter = [twoexpoint - 1]
print (letter)
number += 1
twoexpoint - 1 is the last index of the string you need relative to the input string. So what you need is to start from that index and reduce. In your while loop:
letter = test[twoexpoint- number - 1]
Each iteration you increase number which will reduce the index and reverse the string.
But this way you don't actually use the userstring you already found (except for the length...). Instead of caring for indexes, just reverse the userstring:
for letter in userstring[::-1]:
print(letter)
Explanation we use regex to find the pattern
then we loop for every occurance and we replace the occurance with the reversed string. We can reverse string in python with mystring[::-1] (works for lists too)
Python re documentation Very usefull and you will need it all the time down the coder road :). happy coding!
Very usefull article Check it out!
import re # I recommend using regex
def reverse_string(a):
matches = re.findall(r'\!(.*?)\!', a)
for match in matches:
print("Match found", match)
print("Match reversed", match[::-1])
for i in match[::-1]:
print(i)
In [3]: reverse_string('test test !test! !123asd!')
Match found test
Match reversed tset
t
s
e
t
Match found 123asd
Match reversed dsa321
d
s
a
3
2
1
You're overcomplicating it. Don't bother with an index, simply use reversed() on userstring to cycle through the characters themselves:
userstring = test[expoint+1:twoexpoint]
for letter in reversed(userstring):
print(letter)
Or use a reversed slice:
userstring = test[twoexpoint-1:expoint:-1]
for letter in userstring:
print(letter)
This question already has answers here:
Removing numbers from string [closed]
(8 answers)
Closed 5 years ago.
Im looking to remove every single number in a string. More specifically, i'm looking to remove all numbers in the following codes string
Comp_String = "xxf1,aff242342"
how can one do this. (Obviously inside the code). I have found many answers to questions about removing the actual parts of the code that are letters but not numbers. Please explain aswell what your code is actually doing
You can find the answer here
Removing numbers from string
From this answer:
comp_string = "xxf1,aff242342"
new_string = ''.join([i for i in comp_string if not i.isdigit()])
It creates a new string using .join from a list. That list is created using a list comprehension that iterates through characters in your original string, and excludes all digits.
This will remove any characters that ARE NOT letters, by going through each character and only adding it to the output if it is a letter:
output_string = ""
for char in Comp_String:
if char.isalpha():
output_string = output_string + char
This will remove any characters that ARE numbers, by going through each character and only adding it to the output if it is not a number:
output_string = ""
for char in Comp_String:
if not char.isdigit():
output_string = output_string + char
You can do it with regular expressions using the https://docs.python.org/3.6/library/re.html module. The only regex you need is \d, which notates digits.
from re import sub
comp_string = "xxf1,aff242342"
print(sub(pattern=r"\d", repl=r"", string=comp_string))
This question already has answers here:
List of all unique characters in a string?
(9 answers)
Closed 7 months ago.
I am supposed to find the number of unique characters in a string.
Here's the catch, no arrays or even while loops (although for loop can accomplish this). I can't seem to do it without writing a bunch of ridiculous if-else statements under a for loop checking each char value against each other.
Use this:
len(set("stackoverflow")) # returns 12
Since you said you are not allowed to use set and thus the solution Christian recommended: len(set('aabbcd'))
You can solve it using a for loop like you wanted to like so:
string = 'aabbcd'
unique = []
for char in string[::]:
if char not in unique:
unique.append(char)
print(len(unique))
Output: 4
Please do upload your attempts next time though and let us try and help you with why those did not work. This website isn't for doing homework your assignments for you.
Edit: Replaced list() that you also said you couldn't use.
Count the number of unique characters in a string Python using only for loops and ifel operations
To count the number of unique ASCII letters in a string s:
import string
s = 'AabC'
s = s.lower()
print(sum(1 for c in string.ascii_lowercase if s.count(c) == 1))
If you want to count upper/lower case letters separately then remove s.lower() line and use string.ascii_letters instead of string.ascii_lowercase. The result may differ from len(set(s)) if there could be other symbols in the string such as punctuations e.g., ':!'
So not allowed are; 'while loops', 'sets', 'arrays' (and lists I assume)..
You can create a string with all unique characters and loop through those with a for loop, this way you don't need a list, array array or while loop.
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz,.?*&^%$##!etc"
def unique_count(some_string):
letter_count = 0
for letter in letters:
if letter in some_string:
letter_count += 1
return letter_count
print(unique_count("whatEver#")
// this will print 9 (because E != e )
Perhaps not as elegant because of the long string to match against, but it meets the requirement of not using lists, arrays or while loop.
You can do this way by using only for loop and by applying len() function on list.
def unique_count(word):
k=list()
for x in word:
if x not in k:
k.append(x)
return len(k)
print(unique_count("stackoverflow is goOd"))
//prints 17 because case sensitive and count whitespace
you can also make a function and call it whenever you want just by passing the argument.
def unique_count(word):
k=list()
for x in word:
if x not in k:
k.append(x)
return len(k)
print(unique_count("stackoverflow is goOd"))
//prints 17
This question already has answers here:
python capitalize first letter only
(10 answers)
Closed 9 years ago.
I'd like to capitalize the first letter in a string. The string will be a hash (and therefore mostly numbers), so string.title() won't work, because a string like 85033ba6c would be changed to 85033Ba6C, not 85033Ba6c, because the number seperates words, confusing title(). I'd like to capitalize the first letter of a string, no matter how far into the string the letter is. Is there a function for this?
Using re.sub with count:
>>> strs = '85033ba6c'
>>> re.sub(r'[A-Za-z]',lambda m:m.group(0).upper(),strs,1)
'85033Ba6c'
It is assumed in this answer that there is at least one character in the string where isalpha will return True (otherwise, this raises StopIteration)
i,letter = next(x for x in enumerate(myhash) if x[1].isalpha())
new_string = ''.join((myhash[:i],letter.upper(),myhash[i+1:]))
Here, I pick out the character (and index) of the first alpha character in the string. I turn that character into an uppercase character and I join the rest of the string with it.