Special characters to the end of sentence [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
For a random string such as:
H!i I am f.rom G3?ermany
how can I move all the special characters to the end of the word, for instance:
Hi! I am from. Germany3?

You can try this one :
s = "H!i I am f.rom G3?ermany"
l = []
for i in s.split():
k = [j for j in i if j.isalpha()]
for m in i:
if not m.isalpha():
k.append(m)
l.append(''.join(k))
print(' '.join(l))
It will o/p like :
"Hi! I am from. Germany3?
In python 2x you can do it in single line like :
k = ' '.join([filter(str.isalpha,i)+''.join([j for j in i if not j.isalpha()]) for i in s.split()])

I'm defining special character as anything thats not a-z, A-Z or spaces:
You can split the string into words, use regex to find the special characters in each word, remove them, add them back to the end of the word, then join the words together to create your new string:
import re
string = "H!i I am f.rom G3?ermany"
words = string.split(' ')
pattern = re.compile('[^a-zA-Z\s]')
new = ' '.join([re.sub(pattern, '', w) + ''.join(pattern.findall(w)) for w in words])
That will turn H!i I am f.rom G3?ermany into Hi! I am from. Germany3?

Related

I need help (with def) print out some alphabet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
currently I faced issue with python code
I have two questions relate with "def" code.
1)
I need to print out 6 alphabet which is "K,E,Y,S,N,O"
slimier like under sample
enter image description here
2)
how can I print out this alphabet if user typing one word like "KEY" then print out *mark with KEY
or If user typing "BED" then print out "E"only because we only have alphabet with K,E,Y,S,N,O
if can anyone help me with this two questions? I appreciate that
Thanks
Question 1 need work with 2-dimensional list (list with lists for rows) and I skip this problem.
As for Question 2 you can filter chars in word.
You can treat string "BED" as list of chars (even without using list("BED")) and you can use it in for-loop to check every char with list ["K","E","Y","S","N","O"] (or "KEYSNO") and skip chars "B" and "D"
#my_chars = "KEYSNO" # also works
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
for char in word:
if char in my_chars:
print(char, "- OK")
else:
print(char, "- unknown")
Result:
B - unknown
E - OK
D - unknown
This way you can create new list to keep only correct chars
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
filtered_chars = []
for char in word:
if char in my_chars:
filtered_chars.append(char)
print(filtered_chars)
Result:
['E']
In Python you can write it even shorter using list comprehension
filtered_chars = [char for char in word if char in my_chars]
Eventually you can write it with function filter() like
filtered_chars = list(filter(lambda char: char in my_chars, word))

How to check if a Python string contains letters, numbers and '_' sign but nothing else? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'd like to check if a Python string contains BOTH letter and number, but nothing else. In other words, strings like "A530", "D592" should return True, whereas strings like "ABCDE" (all letters), "000326" (all number), and "A339*加>" (alphanumeric but also has special characters) will return False.
I've seen a lot of sites that show how to check if string contains either letter or number, but not both. This site https://www.geeksforgeeks.org/python-program-to-check-if-a-string-has-at-least-one-letter-and-one-number/ shows how to check both letter and number, but they iterate through each character in the string, which is not very efficient and something I tried to avoid doing if possible.
Solution without regex :)
s=input()
print(not ((all(i.isdigit() for i in s) or (all(i.isalpha() for i in s)) or (any(not i.isalnum() for i in s)))))
If you don't prefer regex then here is the way.
All conditions checked separately. It is Pythonic and readable as well.
Code:
import string
lst = ["A530", "D592", "ABCDE", "000326", "A339*加>"]
str_ascii_digits = string.ascii_letters + string.digits
passed = [s for s in lst if
any(ch in string.ascii_letters for ch in s ) and
any(ch in string.digits for ch in s) and
all((ch in str_ascii_digits for ch in s))]
print(passed)
Output:
['A530', 'D592']
If those string are individual strings, you can use a regex to check that:
import re
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "A530") # Will return an re.Match object
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "A339*加>") # Will return None
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "AAAA") # Will return None
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "0000") # Will return None

How to retain only lowercase text and underscore in string and replace everything else with space? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I need to retain only lowercase text and underscore in a string and replace everything else with space(" ").
say input: text List ? this_word.
required output: text ist this_word
I am trying the regex expression ^[a-z_] but this doesn't seem to work
Here you are:
[^a-z_\s]
Test the regex here
import re
regex = r"[^a-z_\s]"
test_str = " text List ? this_word."
subst = ""
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
Output:
text ist this_word
Test the code here
string = "aBcDeFgH"
new_string = []
for char in string:
if char.islower() or char == "_":
new_string.append(char)
else:
new_string.append(" ")
print(''.join(new_string))
OUTPUT:
a c e g

How to reverse the order of letters in a string in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In python, how do you reverse the order of words in a string and also reverse the order of the letters in the word.
For example, if the input is:
Hello world
The output should be:
olleH dlrow
My attempt:
a=input('Line: ')
print(a[::-1])
Your desired output conflicts with the description of your requirements viz "how do you reverse the order of words in a string and also reverse the order of the letters in the word.". That would simply be the same as reversing the string, which you have already provided as your solution. Instead, to reverse the the letters in each word, but retain the order of those words, you can use split() and a reverse slice ([::-1]) on each word.
s = "Hello world"
for word in s.split():
print word[::-1],
Or, like this:
print ' '.join(word[::-1] for word in s.split())
The above assumes that you do not need to retain the exact whitespace between words.
You may try this using the slice option:
def reverseOrder(strs):
return ''.join([strs[i] for i in xrange(len(strs)-1, -1, -1)])
or better try this:
>>> s='Hello World'
>>> ' '.join(w[::-1] for w in s.split())
'olleH dlrow'

How do I print without space or newline? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In Python2.7
I would like to print my phrase like "THIS IS HOW IT SHOULD LOOK LIKE" instead of
"T H I S I S H O W I T S H O U L D L O O K L I K E"
How do I do it?
It sounds like you're doing something like this:
letters = "THIS IS HOW IT SHOULD LOOK LIKE"
for letter in letters:
print letter,
Which will put a space between each letter during printing.
Instead of printing each letter one at a time, print the string itself.
>>>print letters
THIS IS HOW IT SHOULD LOOK LIKE
If letters is a list of characters and not a string, convert it into a string using join.
print "".join(letters)
If you can't get the letters all in one list for whatever reason, you can use sys.stdout.write to print strings without the trailing space or newline.
import sys
letters = "THIS IS HOW IT SHOULD LOOK LIKE"
for letter in letters:
sys.stdout.write(letter)
Result:
THIS IS HOW IT SHOULD LOOK LIKE

Categories

Resources