在python 3中无空间打印

时间:2012-10-03 00:55:52

标签: printing python-3.x

我是Python的新手,我想知道如何在不增加额外空间的情况下打印多个值。我想要输出ab而不是a b,而不必两次致电print

print("a", end="")
print("b")

另外,我有以下代码:

a = 42
b = 84 

我希望将其值打印为a = 42, b = 84,但如果我这样做

print("a = ", a, ", ", b = ", b)

添加了额外的空格(输出a = 42 , b = 84

而Java风格,

print("a = " + a + ", b = " + b)

提出TypeError

6 个答案:

答案 0 :(得分:22)

您可以使用sep参数来删除空格:

>>> print("a","b","c")
a b c
>>> print("a","b","c",sep="")
abc

我不知道“Java风格”是什么意思;在Python中,你不能以这种方式向(比如说)整数添加字符串,尽管如果ab是字符串,它将起作用。当然,您还有其他几种选择:

>>> print("a = ", a, ", b = ", b, sep="") 
a = 2, b = 3
>>> print("a = " + str(a) + ", b = " + str(b))
a = 2, b = 3
>>> print("a = {}, b = {}".format(a,b))
a = 2, b = 3
>>> print(f"a = {a}, b = {b}")
a = 2, b = 3

最后一个需要Python 3.6或更高版本。对于早期版本,您可以模拟相同的效果(虽然我一般不建议这样做,但它有时会派上用场,并且没有必要假装其他):

>>> print("a = {a}, b = {b}".format(**locals()))
a = 2, b = 3
>>> print("b = {b}, a = {a}".format(**locals()))
b = 3, a = 2

答案 1 :(得分:0)

您也可以使用

print("%d%d" %(a,b))

打印a和b,不以格式化字符串形式的空格分隔。这与c中的类似。

答案 2 :(得分:0)

print()函数的实际语法是

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

您可以看到它具有一个参数sep,其默认值为' '。这就是为什么要在两者之间插入空格。

print("United","States")            #Output: United States
print("United","States",sep="")     #Output: UnitedStates

答案 3 :(得分:0)

print()将自动在参数之间留出空格。

>>> print("a", "b", "c")
a b c

要对间距进行更多控制,可以使用字符串格式:

>>> v0, v1, v2 = "a", "b", "c"
>>> print("%s%s%s" % (v0, v1, v2))
abc
>>> print("%s%s%s".format(v0, v1, v2)
abc
>>> print(f"{v0}{v1}{v2}")
abc

我喜欢以下主题的指南:https://realpython.com/python-f-strings/

答案 4 :(得分:0)

要分隔字符串或值,可以在print()中使用sep参数

print(a,b,sep='')

答案 5 :(得分:-1)

this page上,答案是打印正常文本并在最后使用 package com.thread.test; import java.io.File; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeBodyPart; public class ReadMailThread implements Runnable{ private Thread readMailThread; private String threadName; public ReadMailThread() { readMailThread = new Thread(this); readMailThread.start(); } public ReadMailThread(String s) { threadName = s; System.out.println("creating thread :: "+threadName); } @Override public void run() { System.out.println("Thread Started "+threadName); String saveDirectory = "D:/Ganga/attachment"; Properties props = new Properties(); props.setProperty("mail.store.protocol", "imaps"); try { Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect("imap.gmail.com", "******@gmail.com", "******"); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); /* Message msg = inbox.getMessage(inbox.getMessageCount()); System.out.println("Message Size is "+msg.getSize()/1024 +" KB"); System.out.println("Message Size is "+msg.getSize()/1024*1024 +" MB"); Address[] in = msg.getFrom(); for (Address address : in) { System.out.println("FROM:" + address.toString()); } Multipart mp = (Multipart) msg.getContent(); BodyPart bp = mp.getBodyPart(0); System.out.println("SENT DATE:" + msg.getSentDate()); System.out.println("SUBJECT:" + msg.getSubject()); System.out.println("CONTENT:" + bp.getContent());*/ Message[] messages = inbox.getMessages(); for (int i = 0; i < messages.length; i++) { String contentType = messages[i].getContentType(); String messageContent = ""; String attachFiles = ""; if (contentType.contains("multipart")) { Multipart multiPart = (Multipart) messages[i].getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { String fileName = part.getFileName(); attachFiles += fileName + ", "; part.saveFile(saveDirectory + File.separator + fileName); } else { messageContent = part.getContent().toString(); } } if (attachFiles.length() > 1) { attachFiles = attachFiles.substring(0, attachFiles.length() - 2); } } else if (contentType.contains("text/plain") || contentType.contains("text/html")) { Object content = messages[i].getContent(); if (content != null) { messageContent = content.toString(); } } /*System.out.println(messages[i].getSize() + " bytes long."); System.out.println(messages[i].getSize()/1024 + " KB long."); System.out.println(messages[i].getSize()/1024*1024 + " MB long."); System.out.println(messages[i].getLineCount() + " lines."); String disposition = messages[i].getDisposition(); if (disposition == null){ //Do Nothing }else if (disposition.equals(Part.INLINE)) { System.out.println("This part should be displayed inline"); } else if (disposition.equals(Part.ATTACHMENT)) { System.out.println("This part is an attachment"); String fileName = messages[i].getFileName(); System.out.println("The file name of this attachment is " + fileName); } String description = messages[i].getDescription(); if (description != null) { System.out.println("The description of this message is " + description); }*/ } inbox.close(false); } catch (Exception mex) { mex.printStackTrace(); } } public void start(){ if(readMailThread == null){ readMailThread = new Thread(this, threadName); readMailThread.start(); } } } package com.thread.test; public class MailTest { public MailTest() { } public static void main(String[] args) { System.out.println("Thread Name :"+Thread.currentThread().getName()); ReadMailThread rmt1=new ReadMailThread("remoteThread1"); ReadMailThread rmt2=new ReadMailThread("remoteThread2"); ReadMailThread rmt3=new ReadMailThread("remoteThread3"); ReadMailThread rmt4=new ReadMailThread("remoteThread4"); ReadMailThread rmt5=new ReadMailThread("remoteThread5"); ReadMailThread rmt6=new ReadMailThread("remoteThread6"); ReadMailThread rmt7=new ReadMailThread("remoteThread7"); ReadMailThread rmt8=new ReadMailThread("remoteThread8"); ReadMailThread rmt9=new ReadMailThread("remoteThread9"); ReadMailThread rmt10=new ReadMailThread("remoteThread10"); rmt1.start(); rmt2.start(); rmt3.start(); rmt4.start(); rmt5.start(); rmt6.start(); rmt7.start(); rmt8.start(); rmt9.start(); rmt10.start(); } } package com.equinix.gse.apps.me.tas.app.ec.process.snmp.fivemins; import com.equinix.gse.apps.me.tas.app.ec.dao.snmp.Snmp5MinsDatabaseReadThread; import com.equinix.gse.apps.me.tas.core.TasException; import com.equinix.gse.apps.me.tas.core.util.TasConstants; import org.apache.commons.dbcp.BasicDataSource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * User: vreddy */ @Service public class Snmp5MinsCache { private static final Logger logger = Logger.getLogger(Snmp5MinsCache.class); private static final String CLASS_NAME="Snmp5MinsCache"; private static final String SNMP5MINSDATABASEREADTHREAD="snmp5MinsDatabaseReadThread"; @Autowired private ApplicationContext ac; public Map<String,Long> getCache() throws TasException{ ExecutorService executor = Executors.newFixedThreadPool(TasConstants.THREAD_POOL_SIZE); int startCounter = 1; int endCounter = TasConstants.SNMP_EXDB_BATCH_SIZE; StringBuilder query = new StringBuilder(); query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME from (" ); query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, "); query.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW "); query.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null and "); StringBuilder countQuery = new StringBuilder(); countQuery.append("select count(*) from (" ); countQuery.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, "); countQuery.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW "); countQuery.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null"); Map<String,Long> map = new ConcurrentHashMap<String, Long>(); BasicDataSource dataSource = (BasicDataSource)ac.getBean(TasConstants.DATA_SOURCE); int recordCount = 0; Connection conn = null; ResultSet resultSet = null; try { conn = dataSource.getConnection(); resultSet = conn.createStatement().executeQuery(countQuery.toString()); resultSet.next(); recordCount = resultSet.getInt(1); int timeToExecute= recordCount>0?(recordCount/TasConstants.SNMP_EXDB_BATCH_SIZE)+1:0; for (int i = 0; i < timeToExecute ; i++) { StringBuilder prepareWhereClass = new StringBuilder(); prepareWhereClass.append(" r >= "); prepareWhereClass.append(startCounter); prepareWhereClass.append(" and r <= "); prepareWhereClass.append(endCounter); Snmp5MinsDatabaseReadThread dbRead = (Snmp5MinsDatabaseReadThread) ac.getBean(SNMP5MINSDATABASEREADTHREAD); ((Snmp5MinsDatabaseReadThread)dbRead).setMap(map); ((Snmp5MinsDatabaseReadThread)dbRead).setQuery(query.toString() + prepareWhereClass.toString()); ((Snmp5MinsDatabaseReadThread)dbRead).setDataSource(dataSource); Runnable worker = dbRead; executor.execute(worker); startCounter = endCounter + 1; endCounter = endCounter + TasConstants.SNMP_EXDB_BATCH_SIZE; } } catch (Exception e) { logger.error(e.getMessage(),e); throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e); } finally { try { resultSet.close(); conn.close(); } catch (SQLException e) { logger.error(e.getMessage(),e); throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e); } } executor.shutdown(); while (!executor.isTerminated()) { logger.info("Waiting to process all the thread"); } logger.info("SNMP 5 mins cache size "+map.size()); return map; } } =========================================== package com.equinix.gse.apps.me.tas.app.ec.process.snmp.fivemins; import com.equinix.gse.apps.me.tas.app.ec.dao.snmp.Snmp5MinsDatabaseReadThread; import com.equinix.gse.apps.me.tas.core.TasException; import com.equinix.gse.apps.me.tas.core.util.TasConstants; import org.apache.commons.dbcp.BasicDataSource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * User: vreddy */ @Service public class Snmp5MinsCache { private static final Logger logger = Logger.getLogger(Snmp5MinsCache.class); private static final String CLASS_NAME="Snmp5MinsCache"; private static final String SNMP5MINSDATABASEREADTHREAD="snmp5MinsDatabaseReadThread"; @Autowired private ApplicationContext ac; public Map<String,Long> getCache() throws TasException{ ExecutorService executor = Executors.newFixedThreadPool(TasConstants.THREAD_POOL_SIZE); int startCounter = 1; int endCounter = TasConstants.SNMP_EXDB_BATCH_SIZE; StringBuilder query = new StringBuilder(); query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME from (" ); query.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, "); query.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW "); query.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null and "); StringBuilder countQuery = new StringBuilder(); countQuery.append("select count(*) from (" ); countQuery.append("select CUSTOMER_PORT_ID,IF_INDEX,SWITCH_NAME, "); countQuery.append("row_number() over (order by CUSTOMER_PORT_ID )r from IXP_PARTICIPANT_VIEW "); countQuery.append("where PRODUCT_SHORT_NAME ='EC' ) where IF_INDEX is not null"); Map<String,Long> map = new ConcurrentHashMap<String, Long>(); BasicDataSource dataSource = (BasicDataSource)ac.getBean(TasConstants.DATA_SOURCE); int recordCount = 0; Connection conn = null; ResultSet resultSet = null; try { conn = dataSource.getConnection(); resultSet = conn.createStatement().executeQuery(countQuery.toString()); resultSet.next(); recordCount = resultSet.getInt(1); int timeToExecute= recordCount>0?(recordCount/TasConstants.SNMP_EXDB_BATCH_SIZE)+1:0; for (int i = 0; i < timeToExecute ; i++) { StringBuilder prepareWhereClass = new StringBuilder(); prepareWhereClass.append(" r >= "); prepareWhereClass.append(startCounter); prepareWhereClass.append(" and r <= "); prepareWhereClass.append(endCounter); Snmp5MinsDatabaseReadThread dbRead = (Snmp5MinsDatabaseReadThread) ac.getBean(SNMP5MINSDATABASEREADTHREAD); ((Snmp5MinsDatabaseReadThread)dbRead).setMap(map); ((Snmp5MinsDatabaseReadThread)dbRead).setQuery(query.toString() + prepareWhereClass.toString()); ((Snmp5MinsDatabaseReadThread)dbRead).setDataSource(dataSource); Runnable worker = dbRead; executor.execute(worker); startCounter = endCounter + 1; endCounter = endCounter + TasConstants.SNMP_EXDB_BATCH_SIZE; } } catch (Exception e) { logger.error(e.getMessage(),e); throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e); } finally { try { resultSet.close(); conn.close(); } catch (SQLException e) { logger.error(e.getMessage(),e); throw new TasException(CLASS_NAME, TasConstants.METHOD_GETCACHE,e.getMessage(),e); } } executor.shutdown(); while (!executor.isTerminated()) { logger.info("Waiting to process all the thread"); } logger.info("SNMP 5 mins cache size "+map.size()); return map; } }

所以命令

sep=""

将给出

print("Hole", hole, "Par", par, sep="")

假设"Hole1Par4" hole==1