How can I add a character "-" to a string such as 'ABC-D1234', so it becomes 'ABC-D-1234'?
Also, how can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D12-34' Many thanks.
It depends on the rule you are using to decide where to insert the extra character.
If you want it between the 5th and 6th characters you could try this:
s = s[:5] + '-' + s[5:]
If you want it after the first hyphen and then one more character:
i = s.index('-') + 2
s = s[:i] + '-' + s[i:]
If you want it just before the first digit:
import re
i = re.search('\d', s).start()
s = s[:i] + '-' + s[i:]
Can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D12-34'
Sure:
i = re.search('(?<=\d\d)', s).start()
s = s[:i] + '-' + s[i:]
or:
s = re.sub('(?<=\d\d)', '-', s, 1)
or:
s = re.sub('(\d\d)', r'\1-', s, 1)
You could use slicing:
s = 'ABC-D1234'
s = s[0:5] + '-' + s[5:]
Just for this string?
>>> 'ABC-D1234'.replace('D1', 'D-1')
'ABC-D-1234'
If you're specifically looking for the letter D and the next character 1 (the other answers take care of the general case), you could replace it with D-1:
s = 'ABC-D1234'.replace('D1', 'D-1')
Related
I tried to make just add print(a+b) and I only got what it equals I don't know what to do I can't find it or look for it online.
You are mixing up printing a string vs. printing an expression.
Printing a string like print('hello world') will print the literal message because you've indicated it's a string with quotes.
However, if you provide an expression like print(a+b), it will evaluate that expression (calculate the math) and then print the string representation of that evaluation.
Now, what you want is actually a mix of both, you want to print a string that has certain parts replaced with an expression. This can be done by "adding" strings and expressions together like so:
print(a + '+' + b + '=' + (a+b))
Notice the difference between + without quotes and '+' with quotes. The first is the addition operator, the second is the literal plus character. Let's break down how the print statement parses this. Let's say we have a = 5 and b = 3. First, we evaluate all the expressions:
print(5 + '+' + 3 + '=' + 8)
Now, we have to add a combination of numbers with strings. The + operator acts differently depending on context, but here it will simply convert everything into a string and then "add" them together like letters or words. Now it becomes something like:
print('5' + '+' + '3' + '=' + '8')
Notice how each number is now a string by the surrounding quotes. This parses to:
print('5+3=8')
which prints the literal 5+3=8
You mean like that:
a = int(input("Give me a number man: "))
b = int(input("Give me another number: "))
print(f'print({a} + {b}) = {a + b}')
print(f'print({a} - {b}) = {a - b}')
print(f'print({a} * {b}) = {a * b}')
print(f'print({a} // {b}) = {a // b}')
print("Look at all those maths!")
Output
Give me a number man: 3
Give me another number: 2
print(3 + 2) = 5
print(3 - 2) = 1
print(3 * 2) = 6
print(3 // 2) = 1
Look at all those maths!
So let's say I have a string, like this:
string = '12345+67890'
I want to go back to search for that plus, and add a letter 'H', so the end result would be like this:
string = '12345+h67890
Also, what if I want to get the latest +, so if there is two +'s, I want to get the last +?
Any help would be appreciated!
You could use reverse split to split on the last instance of +, then join with +H:
>>> '+H'.join('123+456+789'.rsplit('+',1))
'123+456+H789'
Convert into list, iterate through list, when you find the plus add an 'h' into the next index.
string = '12345+67890'
stringList = list(string)
i = 0
newString = ''
for i in range(len(stringList)):
if stringList[i] == '+':
stringList.insert(i+1,'h')
for letter in stringList:
newString += letter
print(newString)
Since you asked how to do it with if statements:
i = -1
for i in range(len(my_str)):
if my_str[i] == '+':
plus = i+1 # <- will update every time you see a + symbol
if i != -1:
my_str = my_str[:i] + 'h' + my_str[i:]
Alternatively, you can search backwards:
i = -1
for i in reversed(range(len(my_str))):
if my_str[i] == '+':
plus = i+1 # <- will update every time you see a + symbol
break
if i != -1:
my_str = my_str[:i] + 'h' + my_str[i:]
As others have mentioned you can use built-in functions like find and rfind. My personal choice is to refer to regular expressions for this type of thing:
import re
my_str = re.sub('(.*\+)(.*)',r"\1h\2", my_str))
I am trying to process a list of strings in order to get all my strings with 8 characters. If a string has less than 8 characters I fill as many blank spaces as needed to get an 8 character long string before the last 4 characters. I wrote the following function and tried to apply it to a list of strings, but got a list with None values.
def lengthstring(string):
if len(string) == 5:
new_string = string[0] + " " + string[1:5]
elif len(string) == 6:
new_string = string[0:2] + " " + string[2:6]
elif len(string) == 7:
new_string = string[0:3] + " " + string[3:7]
else:
new_string = string
lp = ['7C246', '7B8451', 'NDKW0745', '5B06833']
labels_with_eight_characters = [lengthstring(string) for string in lp]
Thank you!
Just in case you need a more concise version of the code:
def lengthstring(string):
return (
string if len(string) >= 8
else string[:-4] + ' ' * (8 - len(string)) + string[-4:])
labels_with_eight_characters = list(map(lengthstring, lp))
print(labels_with_eight_characters)
This prints:
['7 C246', '7B 8451', 'NDKW0745', '5B0 6833']
This is because you did not return values in your lengthstring function. After new_string = string, add return new_string and your code should run fine.
a little easier would be to use rjust...
for loc in lp:
print(loc.rjust(8, ' '))
Heres my code
#!/usr/bin/env python
s = raw_input()
n = input()
x = (s + " ") * n
def remove(x):
return x.replace(" ","-")
print remove(x)
Basically its like this
s = abc
n = 2
I want to print abc-abc
but I end up getting abc-abc-
don't know how to do this.
n = input()
x = (s + " ") * n
Assuming you enter 'abc' and '2', the string becomes 'abc abc ' (Note the space at the end). When you replace with -, it replaces the trailing space with a -. A very quick solution would be to use
x.replace(" ", "-", n-1)
The third parameter is the count, so it will replace all but the trailing space.
This code will do the job
'-'.join([s]*n)
for your data it will be abc-abc
How about this solution:
#!/usr/bin/env python
s = raw_input()
n = input()
x = (s + " ") * (n-1)
x += s
def remove(x):
return x.replace(" ","-")
print remove(x)
So the last 's' would not add any space to x and therefor there is no space at the end to turn into a hyphen.
Got stuck with a part of the python script. For example I got 2 domain names like:
domain.com
new.domain1.us
is it possible to count word lenght of every word, splited with dot and put the lenght in brackets before every word like:
(6)domain(3)com
(3)new(7)domain1(2)us
string = 'domain.com'
answer = ''
for x in string.split('.'):
answer += '(' + str(len(x)) + ')' + x
print(answer)
The method split() will split the string at the given char into an array of strings.
len() will return you the length of the given string/array/...
With these two functions you can solve your problem:
domain = "www.google.de"
split_domain = domain.split('.')
domain_with_len = ""
for part in split_domain:
domain_with_len += "(" + str(len(part)) + ")" + part
if you print the domain_with_len you get the following result:
(3)www(6)google(2)de