Python: Add an alphabet to a string - string

Am tryin to add all the alphabet to all the position in a string just one by one, This is the code:
from string import ascii_lowercase
var = 'abc'
for i in ascii_lowercase:
result = [var[:j] + i + var[j:] for j in range(len(var))]
But this is what am getting :
['zabc', 'azbc', 'abzc']
This is what am expecting :
['aabc', 'abac', 'abca','babc','abbc','abcb'...]
Does anyone know how to fix this. Thanks.

You can build the whole list at once using a nested list comprehension
from string import ascii_lowercase
var = 'abc'
result = [var[:n]+c+var[n:] for c in ascii_lowercase for n in range(len(var)+1)]

Related

Cannot remove the right end space of the output string

import random
string = ''
keys = ['car', 'banana', 'groof', 'jump', 'king', 'alley']
temp = random.randint(2,3)
for i in range(temp):
string = string + random.choice(keys) + ' '
string.strip()
print(string)
I'm just learning programming
Even if you use the strip function,
the space on the right end does not disappear.
What did I do wrong?
The strip function returns the modified string but it does't modify the orignal string it only returns it which need to be stored in another string
import random
string = ''
keys = ['car', 'banana', 'groof', 'jump', 'king', 'alley']
temp = random.randint(2,3)
for i in range(temp):
string = string + random.choice(keys) + ' '
str=string.strip()
print(str)
I suggest using a list comprehension along with string join() here:
keys = ["car", "banana", "groof", "jump", "king", "alley"]
temp = random.randint(2,3)
x = ' '.join([random.choice(keys) for i in range(temp)])
print(x)

How to print only int in python from a sentence?

'>>>[123.456, 789.123]
Here i only need output as "123.456, 789.123"
in python what should i do for that?
Previously i had tried this
import geocoder
import re
g = geocoder.ip('me')
x = print(g.latlng)
string = (x)
string = re.sub('[^0-9]', '', string)
print (string)
In fact i want to print my current location so i had first code something like this...
import geocoder
g = geocoder.ip('me')
print(g.latlng)
but this only show the the latitude and longitude
in square brackets [].
So i need those output without brackets because i want to directly find all details using this outputs and that program is not accepting the inputs in square brackets.
I hope you understand so please help me.
You are getting an array not a string!
lat and lng is what you will need to pass
import geocoder
g = geocoder.ip('me')
lat = g.latlng[0]
lng = g.latlng[1]
print(str(lat) + ", " + str(lng))

len(str) giving wrong result after retrieving str from filename

Any idea why I am getting a length of 6 instead of 5?
I created a file called björn-100.png and ran the code using python3:
import os
for f in os.listdir("."):
p = f.find("-")
name = f[:p]
print("name")
print(name)
length = len(name)
print(length)
for a in name:
print(a)
prints out the following:
name
björn
6
b
j
o
̈
r
n
instead of printing out
name
björn
5
b
j
ö
r
n
If you're using python 2.7, you can simply decode the file name as UTF-8 first:
length = len(name.decode('utf-8'))
But since you're using python 3 and can't simply decode a string as if it were a bytearray, I recommend using unicodedata to normalize the string.
import unicodedata
length = len(unicodedata.normalize('NFC', name))
The way to get the correct string with the two dots inside the o char is:
import unicodedata
name = unicodedata.normalize('NFC', name)

Replace slice of string python with string of different size, but maintain structure

so today I was working on a function that removes any quoted strings from a chunk of data, and replaces them with format areas instead ({0}, {1}, etc...).
I ran into a problem, because the output was becoming completely scrambled, as in a {1} was going in a seemingly random place.
I later found out that this was a problem because the replacement of slices in the list changed the list so that it's length was different, and so the previous re matches would not line up (it only worked for the first iteration).
the gathering of the strings worked perfectly, as expected, as this is most certainly not a problem with re.
I've read about mutable sequences, and a bunch of other things as well, but was not able to find anything on this.
what I think i need is something like str.replace but can take slices, instead of a substring.
here is my code:
import re
def rm_strings_from_data(data):
regex = re.compile(r'"(.*?)"')
s = regex.finditer(data)
list_data = list(data)
val = 0
strings = []
for i in s:
string = i.group()
start, end = i.span()
strings.append(string)
list_data[start:end] = '{%d}' % val
val += 1
print(strings, ''.join(list_data), sep='\n\n')
if __name__ == '__main__':
rm_strings_from_data('[hi="hello!" thing="a thing!" other="other thing"]')
i get:
['"hello!"', '"a thing!"', '"other thing"']
[hi={0} thing="a th{1}r="other thing{2}
I would like the output:
['"hello!"', '"a thing!"', '"other thing"']
[hi={0} thing={1} other={2}]
any help would be appreciated. thanks for your time :)
Why not match both key=value parts using regex capture groups like this: (\w+?)=(".*?")
Then it becomes very easy to assemble the lists as needed.
Sample Code:
import re
def rm_strings_from_data(data):
regex = re.compile(r'(\w+?)=(".*?")')
matches = regex.finditer(data)
strings = []
list_data = []
for matchNum, match in enumerate(matches):
matchNum = matchNum + 1
strings.append(match.group(2))
list_data.append((match.group(1) + '={' + str(matchNum) + '} '))
print(strings, '[' + ''.join(list_data) + ']', sep='\n\n')
if __name__ == '__main__':
rm_strings_from_data('[hi="hello!" thing="a thing!" other="other thing"]')

Python - check if string contains special characters, if yes, replace them

I am having a number of strings in the loop, some strings contain "," and some doesn't contain, I want my code to check if there is any "," present in a string remove them and then print the string, and if its not present, print the string as it is.
here is my code:
for x in range(y):
c = containers[x].find("div",{"class":"cong-data"})
meeting = c.p.next_element
print(meeting)
Thanks in advance.
I recommend using Regular Expression sub() function.
import re
string = 'aabcdefg,hijklmnop,qrstu,ssads'
remove_commas = re.sub(',', '', string)
print(string)
print(remove_commas)
output:
aabcdefg,hijklmnop,qrstu,ssads
aabcdefghijklmnopqrstussads

Resources