[英]How can I increase a number in the middle of a string?
So, I have this string:所以,我有这个字符串:
string = ("book_volume_2")
and I want to increase that number to 3, 4 and so on, up to 6我想将该数字增加到 3、4 等等,最多 6
I've tried我试过了
book = ("book_volume_")
book_plus = (book + str(book +1))
I get something like我得到类似的东西
book_volume_2book_volume22
but I'm expecting:但我期待:
book_volume_3
Is there any way to obtain this?有没有办法获得这个?
Thanks!谢谢!
What you want to use are f-strings
您要使用的是
f-strings
for i in range(1,5):
print(f'book_volume_{i}')
I've applied the logic in a for-loop to show how it works.我已经在 for 循环中应用了逻辑来展示它是如何工作的。
But basically, whatever is inside the curly brackets is not considered a string.但基本上,大括号内的任何内容都不会被视为字符串。
eg例如
if I have function myFunc:如果我有 function myFunc:
def myFunc():
return 5
And then I do print(f'book_volume_{myFunc()}')
然后我做
print(f'book_volume_{myFunc()}')
The result will be: book_volume_5
结果将是:
book_volume_5
You need to make the numeric part of the string an integer if you want to increment it.如果要增加字符串的数字部分,则需要将其设为 integer。 Assuming the book name and number are always separated by an underscore you could do something like:
假设书名和编号始终用下划线分隔,您可以执行以下操作:
mystr = "book_volume_2"
book, sep, vol = mystr.rpartition('_')
vol = str(int(vol) + 1)
my_new_str = ''.join([book, sep, vol])
> 'book_volume_3'
If you have a string string = "book_volume_2"
where the last character is a digit, then you can replace that with the next number like this:如果您有一个字符串
string = "book_volume_2"
,其中最后一个字符是数字,那么您可以将其替换为下一个数字,如下所示:
def next_number(book):
base = book[:-1]
digit = int(book[-1])
return base + str(digit + 1)
print(next_number('book_volume_2'))
string = "book_volume_" + input('Enter volume number: ')
print(string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.